jquery验证手机号讲解
原创
©著作权归作者所有:来自51CTO博客作者迷彩编程的原创作品,请联系作者获取转载授权,否则将追究法律责任
如果要做手机号的验证,那么我们需要知道手机号码的号段。
//移动号码归属地支持号段:134 135 136 137 138 139 147 150 151 152 157 158 159 178 182 183 184 187 188
//联通号码归属地支持号段:130 131 132 145 155 156 176 186
//电信号码归属地支持号段:133 153 177 180 181 189
//移动运营商:170
移动:
2G号段(GSM):134-139、150、151、152、158-159;
3G号段(TD-SCDMA):157、187、188、147.
联通:
2G号段(GSM):130-132、155-156;
3G号段(WCDMA):185、186.
电信:
2G号段(CDMA):133、153;
3G号段(CDMA2000):180、189.
可以写出一个正则表达式:var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/;
<input type="text" id="phone" name="phone" />
首先引入一个JQuery框架:
?
1 2
| <script src= "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js" > </script> |
校验手机号的函数:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| //验证手机号 function vailPhone(){ var phone = jQuery( "#phone" ).val(); var flag = false ; var message = "" ; var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/; if (phone == '' ){ message = "手机号码不能为空!" ; } else if (phone.length !=11){ message = "请输入有效的手机号码!" ; } else if (!myreg.test(phone)){ message = "请输入有效的手机号码!" ; } else if (checkPhoneIsExist()){ message = "该手机号码已经被绑定!" ; } else { flag = true ; } if (!flag){ //提示错误效果 //jQuery("#phoneDiv").removeClass().addClass("ui-form-item has-error"); //jQuery("#phoneP").html(""); //jQuery("#phoneP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message); //jQuery("#phone").focus(); } else { //提示正确效果 //jQuery("#phoneDiv").removeClass().addClass("ui-form-item has-success"); //jQuery("#phoneP").html(""); //jQuery("#phoneP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该手机号码可用"); } return flag; } |
发送请求给后台:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| //验证手机号是否存在 function checkPhoneIsExist(){ var phone = jQuery( "#phone" ).val(); var flag = true ; jQuery.ajax( { url: "checkPhone?t=" + ( new Date()).getTime(), data:{phone:phone}, dataType: "json" , type: "GET" , async: false , success: function (data) { var status = data.status; if (status == "0" ){ flag = false ; } } }); return flag; } |
java后端进行校验:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @RequestMapping(value = "/checkPhone" , method = RequestMethod.GET) public void checkPhone(HttpServletRequest request,HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); try { String phone = request.getParameter( "phone" ); String status = "0" ; //写查询逻辑,查出有的话,那么标记为1,否则标记为0 //UserCellphoneAuth userCellphoneAuth = userService.findUserCellphoneAuthByPhone(phone); //if(userCellphoneAuth!=null){ // status = "1"; //} map.put( "status" , status); String data = JSONObject.fromObject(map).toString(); response.getWriter().print(data); response.getWriter().flush(); response.getWriter().close();
} catch (Exception ex) { logger.error(ex.getMessage(), ex); } } |
以上就是本文的全部内容,教大家如何进行jquery验证手机号是否正确,利用正则表达式,大家可以动手试一试。