標籤:jquery Regex 表單驗證 validate 有線電話和手機Regex
環境:
jquery-1.10.1.min.js
jquery.validate.min.js
任務:表單驗證
html:
<form action="" id="myform" method="POST"><table class="" id="table1"><tbody> <tr> <td class=""></td> <td><input type="text" id="name" name="name" value="" size="16" class=""></td> <td class="text_left" style="color:red"></td> </tr> <tr> <td class=""></td> <td><input type="text" id="tel" name="tel" value="" size="16" class=""></td> <td class="text_left" style="color:red"></td> </tr> <tr> <td class=""></td> <td><input type="text" id="addr" name="addr" value="" size="16" class=""></td> <td class="text_left" style="color:red"></td> </tr> <tr> <td class=""></td> <td><input type="text" id="surplusnum" name="surplusnum" value="" size="16" class=""></td> <td class="text_left" style="color:red"></td> </tr> </tbody> </table></form>
jquery:
$(function() {form.init();});//新加驗證規則。// 聯絡電話(手機/電話皆可)驗證。jQuery.validator.addMethod("isTel", function (value, element) { //(區號)-(直撥號)-(分機號)或者11位手機號。//有線電話可以沒有分機號(區號)-(直撥號)。 var mobile = /^(((0\d{2,3})|(0\d{2,3}-))\d{7,8}(-\d{1,4})?)$|^(1[3584]\d{9})$/; if (!mobile.exec(value)) return false; return true;}, "請正確填寫停車點的聯絡電話"); // 只能輸入正整數。jQuery.validator.addMethod("isSurplusnum", function (value, element) { var num = /^[1-9][0-9]{0,2}$/; if (!num.exec(value)) return false; return true;}, "請正確填寫剩餘車輛數");// 驗證表單。var form = function() {return {init : function() {$("#myform").validate({rules : {name : {required : true,maxlength : 100},addr : {required : true,maxlength : 200},tel : {required : true,isTel : "#tel",minlength : 4,maxlength : 18},surplusnum : {required : true,min : 0,isSurplusnum:"#surplusnum",max : 500}},messages : {name : {required : "請輸入名稱",maxlength : "名稱不得超過{0}個字元",},addr : {required : "請輸入地址",maxlength : "地址不得超過{0}個字元",},tel : {required : "請輸入聯絡電話",maxlength : "電話不能超過{0}個字元",isTel : "電話號碼格式不正確",},surplusnum : {required : "請輸入停車點車輛輛數",max : jQuery.format("車輛輛數不得超過{0}輛"),}},errorPlacement : function(error, element) {if (element.parent().is(‘div‘)) {error.appendTo(element.parent().parent().next());} else {error.appendTo(element.parent().next());}}});}};}
協助:
Regex:http://msdn.microsoft.com/zh-cn/library/ae5bf541(VS.80).aspx
validate表單驗證:http://www.jb51.net/article/36067.htm
本文出自 “暗夜” 部落格,請務必保留此出處http://icyore.blog.51cto.com/8486958/1569740
Jquery表單驗證