jQuery.validate.js API
Name Type
validate( options ) Returns: Validator
驗證所選的FORM
valid( ) Returns: Boolean
檢查是否驗證通過
rules( ) Returns: Options
傳回元素的驗證規則
rules( "add", rules ) Returns: Options
增加驗證規則。
rules( "remove", rules ) Returns: Options
删除驗證規則
removeAttrs( attributes ) Returns: Options
删除特殊屬性并且傳回他們
Custom selectors
Name TypeCustom selectors:
Name Type
:blank Returns: Array <Element >
沒有值的篩選器
:filled Returns: Array <Element >
有值的篩選器
:unchecked Returns: Array <Element >
沒選擇的元素的篩選器
Utilities
Name TypeString utilities:
Name Type
jQuery.format( template, argument , argumentN... ) Returns: String
用參數代替模闆中的 {n}。
Validator
validate方法傳回一個Validator對象, 它有很多方法, 讓你能使用引發校驗程式或者改變form的内容. validator對象有很多方法, 但下面隻是列出常用的.
Name TypeValidator methods:
Name Type
form( ) Returns: Boolean
驗證form傳回成功還是失敗
element( element ) Returns: Boolean
驗證單個元素是成功還是失敗
resetForm( ) Returns: undefined
把前面驗證的FORM恢複到驗證前原來的狀态
showErrors( errors ) Returns: undefined
顯示特定的錯誤資訊
There are a few static methods on the validator object:
Name TypeValidator functions:
Name Type
setDefaults( defaults ) Returns: undefined
改變預設的設定
addMethod( name, method, message ) Returns: undefined
添加一個新的驗證方法. 必須包括一個獨一無二的名字,一個JAVASCRIPT的方法和一個預設的資訊
addClassRules( name, rules ) Returns: undefined
增加組合驗證類型 在一個類裡面用多種驗證方法裡比較有用
addClassRules( rules ) Returns: undefined
增加組合驗證類型 在一個類裡面用多種驗證方法裡比較有用,這個是一下子加多個[edit ]
List of built-in Validation methods
A set of standard validation methods is provided:
Name TypeMethods:
Name Type
required( ) Returns: Boolean
必填驗證元素
required( dependency-expression ) Returns: Boolean
必填元素依賴于表達式的結果.
required( dependency-callback ) Returns: Boolean
必填元素依賴于回調函數的結果.
remote( url ) Returns: Boolean
請求遠端校驗。url通常是一個遠端調用方法
minlength( length ) Returns: Boolean
設定最小長度
maxlength( length ) Returns: Boolean
設定最大長度
rangelength( range ) Returns: Boolean
設定一個長度範圍[min,max]
min( value ) Returns: Boolean
設定最小值.
max( value ) Returns: Boolean
設定最大值.
range( range ) Returns: Boolean
設定值的範圍
email( ) Returns: Boolean
驗證電子郵箱格式
url( ) Returns: Boolean
驗證連接配接格式
date( ) Returns: Boolean
驗證日期格式(類似30/30/2008的格式,不驗證日期準确性隻驗證格式)
dateISO( ) Returns: Boolean
研制ISO類型的日期格式
dateDE( ) Returns: Boolean
驗證德式的日期格式(29.04.1994 or 1.1.2006)
number( ) Returns: Boolean
驗證十進制數字(包括小數的)
numberDE( ) Returns: Boolean
Makes the element require a decimal number with german format.
digits( ) Returns: Boolean
驗證整數
creditcard( ) Returns: Boolean
驗證信用卡号
accept( extension ) Returns: Boolean
驗證相同字尾名的字元串
equalTo( other ) Returns: Boolean
驗證兩個輸入框的内容是否相同
Name Type
phoneUS( ) Returns: Boolean
驗證美式的電話号碼
validate ()的可選項
debug:進行調試模式
$(".selector").validate
({
debug: true
})
把調試設定為預設
$.validator.setDefaults({
debug: true
})
submitHandler:用其他方式替代預設的SUBMIT,比如用AJAX的方式送出
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
})
ignore:忽略某些元素不驗證
$("#myform").validate({
ignore: ".ignore"
})
rules: 預設下根據form的classes, attributes, metadata判斷,但也可以在validate函數裡面聲明
Key/value 可自定義規則. Key是對象的名字 value是對象的規則,可以組合使用 class/attribute/metadata rules.
以下代碼特别驗證selector類中name='name'是必填項并且 email是既是必填又要符合email的格式
$(".selector").validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
// compound rule
email: {
required: true,
email: true
}
}
})
messages:更改預設的提示資訊
$(".selector").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of [email protected]"
}
}
})
groups:定義一個組,把幾個地方的出錯資訊同意放在一個地方,用error Placement控制把出錯資訊放在哪裡
$("#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);
},
debug:true
})
nsubmit Boolean Default: true
送出時驗證. 設定唯false就用其他方法去驗證
Code
不用onsubmit驗證,就允許使用者無論用什麼方法去驗證,而是送出時, 用 keyup/blur/click 等方法.
$(".selector").validate({
onsubmit: false
})
onfocusout Boolean Default: true
Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.
Code
Disables onblur validation.
$(".selector").validate({
onfocusout: false
})
onkeyup Boolean Default: true
在keyup時驗證. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event.
Code
Disables onkeyup validation.
$(".selector").validate({
onkeyup: false
})
onclick Boolean Default: true
在checkboxes 和 radio 點選時驗證.
Code
Disables onclick validation of checkboxes and radio buttons.
$(".selector").validate({
onclick: false
})
focusInvalid Boolean Default: true
把焦點聚焦在最後一個動作或者最近的一次出錯上via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
Code
Disables focusing of invalid elements.
$(".selector").validate({
focusInvalid: false
})
focusCleanup Boolean Default: false
如果是true那麼删除出錯類從出錯的元素上并且隐藏出錯資訊當這個元素被聚焦 .避免和 focusInvalid.一起用
Code
Enables cleanup when focusing elements, removing the error class and hiding error messages when an element is focused.
$(".selector").validate({
focusCleanup: true
})
meta String
為了中繼資料使用其他插件你要包裝 你的驗證規則 在他們自己的項目中可以用這個特殊的選項
Tell the validation plugin to look inside a validate-property in metadata for validation rules.
$("#myform").validate({
meta: "validate",
submitHandler: function() { alert("Submitted!") }
})
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<mce:script src="http://code.jquery.com/jquery-latest.js" mce_src="http://code.jquery.com/jquery-latest.js"></mce:script>
<mce:script type="text/javascript"><!--
$(document).ready(function(){
$("#myform").validate({
meta: "validate",
submitHandler: function() { alert("Submitted!") }
})
});
// --></mce:script>
</head>
<body>
<mce:script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.metadata.js" mce_src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.metadata.js"></mce:script>
<mce:script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js" mce_src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></mce:script>
<form id="myform">
<input type="text" name="email" class="{validate:{ required: true, email:true }}" />
<br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
errorClass String Default: "error"
建立錯誤類的名字為了去尋找存在的錯誤标簽和增加它到驗證失敗的元素中去。
Code
Sets the error class to "invalid".
$(".selector").validate({
errorClass: "invalid"
})
errorElement String Default: "label"
設定錯誤的元素,預設的是label你可以改成em.Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, no matter the element type).
Code
Sets the error element to "em".
$(".selector").validate
errorElement: "em"
})
wrapper String
在出錯資訊外用其他的元素包裝一層。Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.
Code
Wrap each error element with a list item, useful when using an ordered or unordered list as the error container.
$(".selector").validate({
wrapper: "li"
})
errorLabelContainer Selector
把錯誤資訊統一放在一個容器裡面。Hide and show this container when validating.
All error labels are displayed inside an unordered list with the ID "messageBox", as specified by the selector passed as errorContainer option. All error elements are wrapped inside an li element, to create a list of messages.
$("#myform").validate({
errorLabelContainer: "#messageBox",
wrapper: "li",
submitHandler: function() { alert("Submitted!") }
})
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<mce:script src="http://code.jquery.com/jquery-latest.js" mce_src="http://code.jquery.com/jquery-latest.js"></mce:script>
<mce:script type="text/javascript"><!--
$(document).ready(function(){
$("#myform").validate({
errorLabelContainer: "#messageBox",
wrapper: "li",
submitHandler: function() { alert("Submitted!") }
})
});
// --></mce:script>
</head>
<body>
<mce:script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js" mce_src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></mce:script>
<ul id="messageBox"></ul>
<form id="myform" action="/login" method="post">
<label>Firstname</label>
<input name="fname" class="required" />
<label>Lastname</label>
<input name="lname" title="Your lastname, please!" class="required" />
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
errorContainer Selector
顯示或者隐藏驗證資訊
使用一個額外的容器去顯示錯誤資訊
Uses an additonal container for error messages. The elements given as the errorContainer are all shown and hidden when errors occur. But the error labels themselve are added to the element(s) given as errorLabelContainer, here an unordered list. Therefore the error labels are also wrapped into li elements (wrapper option).
$("#myform").validate({
errorContainer: "#messageBox1, #messageBox2",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li", debug:true,
submitHandler: function() { alert("Submitted!") }
})
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<mce:script src="http://code.jquery.com/jquery-latest.js" mce_src="http://code.jquery.com/jquery-latest.js"></mce:script>
<mce:script type="text/javascript"><!--
$(document).ready(function(){
$("#myform").validate({
errorContainer: "#messageBox1, #messageBox2",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li", debug:true,
submitHandler: function() { alert("Submitted!") }
})
});
// --></mce:script>
<mce:style><!--
#messageBox1, #messageBox2 { display: none }
--></mce:style><style mce_bogus="1">#messageBox1, #messageBox2 { display: none }</style>
</head>
<body>
<mce:script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js" mce_src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></mce:script>
<div id="messageBox1">
<ul></ul>
</div>
<form id="myform" action="/login" method="post">
<label>Firstname</label>
<input name="fname" class="required" />
<label>Lastname</label>
<input name="lname" title="Your lastname, please!" class="required" />
<br/>
<input type="submit" value="Submit"/>
</form>
<div id="messageBox2">
<h3>There are errors in your form, see details above!</h3>
</div>
</body>
</html>
showErrors Callback Default: None, uses built-in message disply.
得到錯誤的顯示句柄
Gets the map of errors as the first argument and and array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().
Code
Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display.
$(".selector").validate({
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below.");
this.defaultShowErrors();
}
})
errorPlacement Callback Default: 把錯誤label放在驗證的元素後面
可選錯誤label的放置位置. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.
Use a table layout for the form, placing error messags in the next cell after the input.
$("#myform").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
debug:true
})
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<mce:script src="http://code.jquery.com/jquery-latest.js" mce_src="http://code.jquery.com/jquery-latest.js"></mce:script>
<mce:script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js" mce_src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></mce:script>
<mce:script type="text/javascript"><!--
$(document).ready(function(){
$("#myform").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
debug:true
})
});
// --></mce:script>
</head>
<body>
<form id="myform" action="/login" method="post">
<table>
<tr>
<td><label>Firstname</label>
<td><input name="fname" class="required" value="Pete" /></td>
<td></td>
</tr>
<tr>
<td><label>Lastname</label></td>
<td><input name="lname" title="Your lastname, please!" class="required" /></td>
<td></td>
</tr>
<tr>
<td></td><td><input type="submit" value="Submit"/></td><td></td>
</table>
</form>
</body>
</html>
success String , Callback
成功時的class.If specified, the error label is displayed to show a valid element. If a String is given, its added as a class to the label. If a Function is given, its called with the label (as a jQuery object) as its only argument. That can be used to add a text like "ok!".
添加"valid" 到驗證驗證元素, 在CSS中定義的樣式
$("#myform").validate({
success: "valid",
submitHandler: function() { alert("Submitted!") }
})
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<mce:script src="http://code.jquery.com/jquery-latest.js" mce_src="http://code.jquery.com/jquery-latest.js"></mce:script>
<mce:script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js" mce_src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></mce:script>
<mce:script type="text/javascript"><!--
$(document).ready(function(){
$("#myform").validate({
success: "valid",
submitHandler: function() { alert("Submitted!") }
})
});
// --></mce:script>
<mce:style><!--
label.valid {
background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
height:16px;
width:16px;
display: block;
position: absolute;
top: 4px;
left: 152px;
}
--></mce:style><style mce_bogus="1">label.valid {
background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
height:16px;
width:16px;
display: block;
position: absolute;
top: 4px;
left: 152px;
}</style>
</head>
<body>
<form id="myform">
<input type="text" name="email" class="required" />
<br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
添加"valid" 到驗證驗證元素, 在CSS中定義的樣式,并加入“ok”的文字
$("#myform").validate({
success: function(label) {
label.addClass("valid").text("Ok!")
},
submitHandler: function() { alert("Submitted!") }
})
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<mce:script src="http://code.jquery.com/jquery-latest.js" mce_src="http://code.jquery.com/jquery-latest.js"></mce:script>
<mce:script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js" mce_src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></mce:script>
<mce:script type="text/javascript"><!--
$(document).ready(function(){
$("#myform").validate({
success: function(label) {
label.addClass("valid").text("Ok!")
},
submitHandler: function() { alert("Submitted!") }
})
});
// --></mce:script>
<mce:style><!--
label.valid {
background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
height:16px;
width:16px;
display: block;
position: absolute;
top: 4px;
left: 152px;
padding-left: 18px;
}
--></mce:style><style mce_bogus="1">label.valid {
background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
height:16px;
width:16px;
display: block;
position: absolute;
top: 4px;
left: 152px;
padding-left: 18px;
}</style>
</head>
<body>
<form id="myform">
<input type="text" name="email" class="required" />
<br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
highlight Callback Default: Adds errorClass (see the option) to the Element
高亮顯示錯誤資訊。 或者說重寫出錯時的出錯元素的顯示。Override to decide which fields and how to highlight.
Code
Highlights an invalid element by fading it out and in again.
$(".selector").validate({
highlight: function(element, errorClass) {
$(element).fadeOut(function() {
$(element).fadeIn()
})
}
})
Code
Adds the error class to both the invalid element and it's label
$(".selector").validate({
highlight: function(element, errorClass) {
$(element).addClass(errorClass);
$(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
$(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
}
});
unhighlight Callback Default: 預設是去掉error類
Called to revert changes made by option highlight, same arguments as highlight.
作者:KKcat