<script src="../js/jquery.js" type="text/javascript"></script>
<script src="../js/jquery.validate.js" type="text/javascript"></script>
一、validate()方法
rules裏的常用驗證規則:
1.required:輸入字段是否爲必須。
2.remote(調用形式,remote:“check.php”):以Ajax形式調用驗證方法進行驗證。
3.email:輸入字段是否爲正確的電子郵件格式。
4.url:輸入字段是否爲正確的網址格式。
5.date:輸入字段是否爲正確日期格式。
6.dateISO:輸入字段是否爲”2014-11-12“格式,但不驗證日期是否有效。
7.number:輸入字段是否爲合法數字。
8.digits:輸入字段是否爲整數。
9.creditcard:輸入字段是否爲合法信用卡號。
10.equalTo(調用格式,equalTo:選擇器):輸入字段是否與選擇器的字段相等。
11.accept:上傳文件格式是否匹配,一般一後綴名作爲判定標準。
12.maxlength(調用格式,maxlength:數字):輸入字段最大長度是否爲特定長度,漢字記爲一個字符串。
13.minlength(調用格式,minlength:數字):輸入字段最小長度是否爲特定長度,漢字記爲一個字符串。
14.rangelength(調用格式,rangelength:[數字1,數字2]):輸入字段長度是否介於數字1和數字2之間,數字1小於數字2。
15.range(調用格式,range:[數字1,數字2]):輸入值是否介於數字1和數字2之間,數字1小於數字2。
16.max(調用格式,max:數字1):輸入值是否小於數字1(最大爲數字1)。
17.min(調用格式,min:數字1):輸入值是否大於數字1(最小爲數字2)。
18.extension(調用格式,extension: "文件拓展名|文件拓展名"):上傳元素是否符合相應後綴名,默認爲,extension: "png|?jpeg|gif"。
19.require_from_group(調用格式,require_from_group: [數字, 元素組羣]):驗證一組元素是否添加夠一定數量。
20.phoneUS:驗證是否是一個合法的美國電話號碼。
規則中冒號右邊的true、false、數值等都可以換成擁有這樣值的表達式或方法用來進行驗證:
required:"#aa:checked" 表達式的值爲真,則需要驗證。
required:function(){} 返回爲真,表示需要驗證。
案例(remote驗證):
remote: "check-email.php"
案例(remote驗證):
remote: {
url: "check-email.php", //後臺處理程序
type: "post", //數據發送方式
dataType: "json", //接受數據格式
data: { //要傳遞的數據
username: function() {
return $("#username").val();
}
}
}
案例(accept文件類型驗證):
$( "#myform" ).validate({
rules: {
field:{
required:
true,
accept:
"audio/*"
}
}
});
案例(extension文件後綴名驗證):
$( "#myform" ).validate({
rules: {
field: {
required: true,
extension: "xls|csv"
}
}
});
案例(require_from_group驗證至少填寫一個):
<body>
<formid="myform">
<labelfor="mobile_phone">Mobile phone:</label>
<inputclass="left phone-group"id="mobile_phone"name="mobile_phone">
<br/>
<labelfor="home_phone">Home phone:</label>
<inputclass="left phone-group"id="home_phone"name="home_phone">
<br/>
<labelfor="work_phone">Work phone:</label>
<inputclass="left phone-group"id="Work_phone"name="work_phone">
<br/>
<inputtype="submit"value="Validate!">
</form>
<scriptsrc="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug:
true,
success:
"valid"
});
$( "#myform" ).validate({
rules: {
mobile_phone: {
require_from_group: [1,".phone-group"]
},
home_phone: {
require_from_group: [1,".phone-group"]
},
work_phone: {
require_from_group: [1,".phone-group"]
}
}
});
</script>
</body>
message規則:
相對於每一個rules的規則,都會有相應的message。默認的message:
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
dateDE: "Bitte geben Sie ein gültiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: $.validator.format("Please enter no more than {0} characters."),
minlength: $.validator.format("Please enter at least {0} characters."),
rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
range: $.validator.format("Please enter a value between {0} and {1}."),
max: $.validator.format("Please enter a value less than or equal to {0}."),
min: $.validator.format("Please enter a value greater than or equal to {0}.")
如果頁面沒有爲規則編寫特定的message,則會返回默認。
案例(validate的頁面調用形式):
$(document).ready(function() {
$("#signupForm").validate({ //要用JQuery的選擇器來調用validate方法。
rules: { //編寫過濾規則
firstname: "required", //1.可以直接用字符串“required”,表示此字段爲必須。
email: {
required: true, //2.同樣可以required:true,表示此字段爲必須。
email: true
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: { //
firstname: "請輸入姓名",
email: {
required: "請輸入Email地址",
email: "請輸入正確的email地址"
},
password: {
required: "請輸入密碼",
minlength: jQuery.format("密碼不能小於{0}個字 符")
},
confirm_password: {
required: "請輸入確認密碼",
minlength: "確認密碼不能小於5個字符",
equalTo: "兩次輸入密碼不一致不一致"
}
}
});
});
案例(validate的js導入調用形式):
<script src="../js/jquery.validatefunction.js" type="text/javascript"></script>
首先導入js文件,然後調用validate的方法。
$().ready(function() {
$("#signupForm").validate();
});
submitHandler規則:
替換默認提交方式,進行自定義提交,加入提醒等。
案例(代替原本submit):
$().ready(function() {
$("#signupForm").validate({
submitHandler:function(form){
alert("submitted");
form.submit();
}
});
});
案例(Ajax提交):
$(".selector").validate({
submitHandler: function(form)
{
$(form).ajaxSubmit();
}
})
案例(爲提交添加提醒):
$.validator.setDefaults({
submitHandler: function(form) { alert("submitted!");form.submit(); }
});
invalidHandler規則:
無效表單被提交,回調方法。可以自定義回調信息。
案例(event爲自定義事件對象,validator爲表單驗證器):
$(".selector").validate({
invalidHandler:
function(event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors ==1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors +' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
});
debug規則:
當值爲true時,只檢驗數據有效性,不進行提交。
案例(表單驗證):
$().ready(function() {
$("#signupForm").validate({
debug:true
});
});
案例(全頁面驗證):
$.validator.setDefaults({
debug: true
})
ignore規則,默認爲”hidden“:
設定特定元素不需要驗證。
案例:
ignore: ".ignore" //選擇器內容不需要驗證。
groups規則:
案例:
$("#myform").validate({
groups: {
username:
"fname lname"
},
errorPlacement:
function(error, element) {
if (element.attr("name") =="fname" || element.attr("name") =="lname"
) {
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
errorPlacement規則:
指定驗證信息顯示的位置。默認的位置是在驗證元素的後面。
案例:
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
errorClass規則:
指定驗證錯誤後,提示信息的class屬性,用以自定義提示信息的樣式。默認爲”error“。
案例:
$(".selector").validate({
errorClass:"invalid"
})
errorElement規則:
指定標記驗證提示信息的標籤,默認爲”label‘,可以設爲“em”。
案例:
$(".selector").validate
errorElement:"em"
})
errorContainer規則:
根據驗證結果顯示或者隱藏錯誤提示容器元素。
errorLabelContainer規則:
指定驗證失敗提示信息的存放容器。
案例:
$("#myform").validate({
errorLabelContainer:"#messageBox",
wrapper:"li",
submitHandler:function() {
alert("Submitted!")
}
})
wrapper規則:
指定元素將上面errorElement規則指定的信息存放標籤包起來。
案例:
$(".selector").validate({
wrapper:"li"
})
success規則:
指定驗證成功後的下一步操作。可以是函數,或者字符串(字符串被當做css類來處理)。
onsubmit規則:
默認爲true,則在提交時驗證,否則在另外的觸發條件下驗證。
案例:
$(".selector").validate({
onsubmit:false
})
onfocusout規則:
默認爲true,則在失去焦點時驗證,否則在另外的觸發條件下驗證。
案例:
$(".selector").validate({
onfocusout:false
})
onkeyup規則:
默認爲true,則在按鍵按下時驗證,否則在另外的觸發條件下驗證。
案例:
$(".selector").validate({
onkeyup:false
})
onclick規則:
默認爲true,則在點擊事件中驗證,否則在另外的觸發條件下驗證。
案例:
$(".selector").validate({
onclick:false
})
focusInvalid規則:
默認爲true,提交時驗證未通過的第一個元素獲得焦點。
案例:
$(".selector").validate({
focusInvalid:false
})
focusCleanup規則:
默認爲false,在驗證未通過元素獲得焦點時,隱藏錯誤信息提示。避免和focusInvalid一起使用。
案例:
$(".selector").validate({
focusCleanup:true
})
showErrors規則:
跟一個函數,可以顯示總共有多少個未通過驗證的元素。
案例:
$(".selector").validate({
showErrors:function(errorMap,errorList) {
$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");
this.defaultShowErrors();
}
})
highlight規則:
可以給未通過驗證的元素加效果、閃爍等。
案例:
$(".selector").validate({
highlight:
function(element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
$(element.form).find("label[for=" + element.id +"]")
.addClass(errorClass);
},
unhighlight:
function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass);
$(element.form).find("label[for=" + element.id +"]")
.removeClass(errorClass);
}
});
unhighlight規則:
從高亮狀態恢復平常,參數與highlight相同。
ignoreTitle規則:
忽略message的標題欄。默認爲false。
案例:
$(".selector").validate({
ignoreTitle:
true
});
addMethod規則(添加自定義驗證):
調用方式,addMethod:name, method, message。第一個參數爲驗證器名字,第二個爲驗證函數、第三個爲驗證返回信息。
案例:
// 中文字兩個字節
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
var length = value.length;
for(var i = 0; i < value.length; i++){
if(value.charCodeAt(i) > 127){
length++;
}
}
return this.optional(element) || ( length >= param[0] && length <= param[1] );
}, $.validator.format("請確保輸入的值在{0}-{1}個字節之間(一箇中文字算2個字節)"));
案例:
// 郵政編碼驗證
jQuery.validator.addMethod("isZipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "請正確填寫您的郵政編碼");
二、rules組方法
.rules():讀取驗證規則。
.rules("add",rules):添加驗證規則。
.rules("remove",rules):移除驗證規則,不指定rules,將移除所有規則。
案例(添加規則,最小長度爲2):
$( "#myinput" ).rules("add", {
minlength:
2
});
案例(添加規則,並自定義message):
$( "#myinput" ).rules("add", {
required:
true,
minlength:
2,
messages: {
required:
"Required input",
minlength: jQuery.format("Please, at least {0} characters are necessary")
}
});
案例(刪除所有驗證規則):
$( "#myinput" ).rules( "remove" ); |
案例(刪除指定驗證規則,根據驗證規則名指定):
$( "#myinput" ).rules("remove","min max" );
rules規則指定形式:
1.驗證規則如果沒有參數,可以直接寫在驗證元素的class屬性中。
2.帶參數的驗證規則,可以作爲驗證元素屬性值來驗證。
3.都以metadata形式調用。
4.都以validate的rules形式調用。
三、valid()方法
驗證元素中的所有需要驗證子元素,是否合法有效。
案例:
<body>
<formid="myform">
<formid="myform">
<inputtype="text"name="name"required>
<br>
<buttontype="button">Validate!</button>
</form>
</form>
<scriptsrc="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug:
true,
success:
"valid"
});
var form = $("#myform" );
form.validate();
$( "button" ).click(function() {
alert(
"Valid: " + form.valid() );
});
</script>
</body>
四、關於選擇框的驗證
redio、checkbox、select選擇驗證:
1.radio 的 required 表示必須選中一個。
案例(redio必須選一個):
<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />
<input type="radio" id="gender_female" value="f" name="gender"/>
2.checkbox 的 required 表示必須選中。
案例(checkbox必須選中):
<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />
3.checkbox 的 minlength 表示必須選中的最小個數,maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。
案例(checkbox限定選定個數):
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />
4.select 的 required 表示選中的 value 不能爲空。
案例(select選擇不爲空):
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
<option value=""></option>
<option value="1">Buga</option>
<option value="2">Baga</option>
<option value="3">Oi</option>
</select>
5.select 的 minlength 表示選中的最小個數(可多選的 select),maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。
案例(select多選限定):
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
<option value="b">Banana</option>
<option value="a">Apple</option>
<option value="p">Peach</option>
<option value="t">Turtle</option>
</select>
validate包含的選擇驗證
1、:unchecked Selector
選擇所有未被選中的元素。
案例:
<body>
<formid="myform">
<form>
<inputtype="checkbox"name="newsletter"checked="checked"value="Hourly"
/>
<inputtype="checkbox"name="newsletter"value="Daily"
/>
<inputtype="checkbox"name="newsletter"value="Weekly"
/>
<inputtype="checkbox"name="newsletter"checked="checked"value="Monthly"
/>
<inputtype="checkbox"name="newsletter"value="Yearly"
/>
</form>
<div></div>
</form>
<scriptsrc="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug:
true,
success:
"valid"
});
functioncountUnchecked() {
var n = $("input:unchecked" ).length;
$( "div" ).text(n + (n ==1 ?" is" :" are") +" unchecked!" );
}
countUnchecked();
$( ":checkbox" ).click( countUnchecked );
</script>
</body>
2、:filled Selector
選擇所有被填充的元素。
案例:
<body>
<formid="myform">
<div>Mouseover to see the value of each input</div>
<inputvalue=""title='""'>
<inputvalue=" "title='" "'>
<inputvalue="abc"title='"abc"'>
</form>
<scriptsrc="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug:
true,
success:
"valid"
});
$( "input:filled" ).css("background-color","#bbbbff" );
</script>
</body>
3、:blank Selector
選擇空白的元素。
案例:
<body>
<formid="myform">
<div>Mouseover to see the value of each input</div>
<inputvalue=""title='""'>
<inputvalue=" "title='" "'>
<inputvalue="abc"title='"abc"'>
</form>
<scriptsrc="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<scriptsrc="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug:
true,
success:
"valid"
});
$( "input:blank" ).css("background-color","#bbbbff" );
</script>
</body>
五、validate方法會返回一個validator的對象,validator提供了一些方法供調用。
1.Validator.form()方法:驗證form是否有效,有效返回true,否則爲false。
案例:
var validator = $("#myform" ).validate();
validator.form();
2.Validator.element()方法:驗證一個元素是否有效,有效返回true,否則爲false。
案例:
var validator = $("#myform" ).validate();
validator.element(
"#myselect" );
3.Validator.resetForm()方法:復位控制表單。
案例:
var validator = $("#myform" ).validate();
validator.resetForm();
4.Validator.showErrors():自定義驗證錯誤信息。
案例:
var validator = $("#myshowErrors" ).validate();
validator.showErrors({
"firstname":"I know that your firstname is Pete, Pete!"
});
5.Validator.numberOfInvalids(): 返回無效元素的數目。
案例:
var validator = $( "#myform" ).validate({
invalidHandler: function() {
$( "#summary" ).text( validator.numberOfInvalids() + " field(s) are invalid" );
}
});
6.jQuery.validator.addMethod():添加自定義的驗證規則,調用模式,jQuery.validator.addMethod( name, method [, message ] )。
name,爲規則的調用名,必須定義。message,爲自定義默認驗證信息。
method,驗證具體實現,擁有三個參數:
1.value:驗證元素的值。
2.element:需要驗證的元素。
3.params:爲method指定參數。
案例(驗證給定值是否等於兩參數之和):
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {0} + {1}"));
7.jQuery.validator.format():以定義形式替換佔位符。調用形式,jQuery.validator.format( template, argument, argumentN… )。
template:定義模板。
argument:插入的第一個參數或字符串數組。
argumentN:插入的第n個參數等等。
案例(format中佔位符由模板中“abc”來代替,然後結果爲:“abc” is not a valid value。):
var template = jQuery.validator.format("{0} is not a valid value");
// later, results in 'abc is not a valid value'
alert(template("abc"));
8.jQuery.validator.setDefaults():爲驗證器設置默認值。
案例(將validation的debug設置默認爲true):
jQuery.validator.setDefaults({
debug: true
});
9.jQuery.validator.addClassRules():定義規則的集合類。
案例(定義一個驗證規則名字爲“name”,包含rule原本的幾條規則):
required: true,
minlength: 2
});
name: {
required: true,
minlength: 2
},
zip: {
required: true,
digits: true,
minlength: 5,
maxlength: 5
}
});