$("form").validate({ // debug:true,//debug时不会提交表单 rules:{//rules和messages,规则和对应消息 name:"required", password:"required" },messages:{ name:"name is required", password:"password is required" }, submitHandler :function(){//提交表单时调用,替代默认提交表单的行为 alert("submitHandler"); },invalidHandler:function(){//验证不通过时调用 alert("invalidHandler"); },onsubmit:true,//是否提交表单时触发 onfocusout:function(element) {$(element).valid()},//用boolean会报错,需要用function对象blur时验证 onkeyup:function(element) {$(element).valid()},//用boolean会报错,需要用function对象keyup时验证 focusInvalid:false ,//验证后让未通过验证的第一个表单元素获得焦点 errorClass:"error",//定义错误信息的class showErrors:function(){//显示错误信息调用此方法,可以自定义错误显示 this.defaultShowErrors(); }, focusCleanup:true//focus对应对象时隐藏错误提示 });
Validator还有一些有用的方法:
jQuery.validator.addMethod()
– Add a custom validation method.-
jQuery.validator.format()
– Replaces {n} placeholders with arguments. //格式化字符串 jQuery.validator.setDefaults()
– Modify default settings for validation.-
jQuery.validator.addClassRules()
– Add a compound class method. Validator.form()
– Validates the form.Validator.element()
– Validates a single element.-
Validator.resetForm()
– Resets the controlled form. //重置表单 Validator.showErrors()
– Show the specified messages.Validator.numberOfInvalids()
– Returns the number of invalid fields.:blank
– Selects all elements with a blank value.:filled
– Selects all elements with a filled value.:unchecked
– Selects all elements that are unchecked.
下面是从官网copy的详细介绍,方便查找。
validate( [options ] )Returns: Validator
Description: Validates the selected form.
-
validate( [options ] )
-
optionsType: Object
-
debug (default:
false
)Type: BooleanEnables debug mode. If true, the form is not submitted and certain errors are displayed on the console (will check if awindow.console
property exists). Try to enable when a form is just submitted instead of validation stopping the submit.Example: Prevents the form from submitting and tries to help setting up the validation with warnings about missing methods and other debug messages.
123$(".selector").validate({
debug: true
});
-
submitHandler (default:
native form submit
)Type: Function()Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.Example: Submits the form via Ajax when valid.
12345$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
Example: Use submitHandler to process something and then using the default submit. Note that “form” refers to a DOM element, this way the validation isn’t triggered again.
123456$(".selector").validate({
submitHandler: function(form) {
// do other stuff for a valid form
form.submit();
}
});
The callback gets passed one argument:
-
formType: ElementThe form currently being validated, as a DOMElement.
-
-
invalidHandlerType: Function()Callback for custom code when an invalid form is submitted. Called with a event object as the first argument, and the validator as the second.
Example: Displays a message above the form, indicating how many fields are invalid when the user tries to submit an invalid form.
123456789101112131415$(".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();
}
}
});
The callback gets passed two arguments:
-
ignore (default:
":hidden"
)Type: SelectorElements to ignore when validating, simply filtering them out. jQuery’s not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.Example: Ignores all element with the class “ignore” when validating.
123$("#myform").validate({
ignore: ".ignore"
});
-
rules (default:
rules are read from markup (classes, attributes, data)
)Type: ObjectKey/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions. See the second example below for details.Example: Specifies a name element as required and an email element as required (using the shortcut for a single rule) and a valid email address (using another object literal).
1234567891011$(".selector").validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
// compound rule
email: {
required: true,
email: true
}
}
});
Example: Specifies a contact element as required and as email address, the latter depending on a checkbox being checked for contacting via email.
123456789101112$(".selector").validate({
rules: {
contact: {
required: true,
email: {
depends: function(element) {
return $("#contactform_email:checked")
}
}
}
}
});
-
messages (default:
the default message for the method used
)Type: ObjectKey/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator and with the rule’s parameters as the first and the element as the second arugment, it must return a String to display as the message.Example: Specifies a name element as required and an email element as required and a valid email address. A single message is specified for the name element, and two messages for email.
12345678910111213141516$(".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 name@domain.com"
}
}
});
Example: Validates the name-field as required and having at least two characters. Provides a callback message using jQuery.format to avoid having to specify the parameter in two places.
1234567891011121314$(".selector").validate({
rules: {
name: {
required: true,
minlength: 2
}
},
messages: {
name: {
required: "We need your email address to contact you",
minlength: jQuery.format("At least {0} characters required!")
}
}
});
-
groupsType: ObjectSpecify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed.
Example: Use a table layout for the form, placing error messags in the next cell after the input.
123456789101112$("#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);
}
}
});
-
onsubmit (default:
true
)Type: BooleanValidate the form on submit. Set to false to use only other events for validation.Set to a Function to decide yourself when to run validation.
A boolean true is not a valid value.
Example: Disables onsubmit validation, allowing the user to submit whatever he wants, while still validating on keyup/blur/click events (if not specified otherwise).
123$(".selector").validate({
onsubmit: false
});
-
onfocusoutValidate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.
Set to a Function to decide yourself when to run validation.
A boolean true is not a valid value.
Example: Disables onblur validation.
123$(".selector").validate({
onfocusout: false
});
The callback gets passed two arguments:
-
onkeyupValidate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable.
Set to a Function to decide yourself when to run validation.
A boolean true is not a valid value.
Example: Disables onkeyup validation.
123$(".selector").validate({
onkeyup: false
});
The callback gets passed two arguments:
-
onclickValidate checkboxes and radio buttons on click. Set to false to disable.
Set to a Function to decide yourself when to run validation.
A boolean true is not a valid value.
Example: Disables onclick validation of checkboxes and radio buttons.
123$(".selector").validate({
onclick: false
});
The callback gets passed two arguments:
-
focusInvalid (default:
true
)Type: BooleanFocus the last active or first invalid element on submit 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.Example: Disables focusing of invalid elements.
123$(".selector").validate({
focusInvalid: false
});
-
focusCleanup (default:
false
)Type: BooleanIf enabled, removes the errorClass from the invalid elements and hides all errors messages whenever the element is focused. Avoid combination with focusInvalid.Example: Enables cleanup when focusing elements, removing the error class and hiding error messages when an element is focused.
123$(".selector").validate({
focusCleanup: true
});
-
errorClass (default:
"error"
)Type: StringUse this class to create error labels, to look for existing error labels and to add it to invalid elements.Example: Sets the error class to “invalid”.
123$(".selector").validate({
errorClass: "invalid"
});
-
validClass (default:
"valid"
)Type: StringThis class is added to an element after it was validated and considered valid.Example: Sets the valid class to “success”.
123$(".selector").validate({
validClass: "success"
});
-
errorElement (default:
"label"
)Type: StringUse 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).Example: Sets the error element to “em”.
123$(".selector").validate({
errorElement: "em"
});
-
wrapper (default:
window
)Type: StringWrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.Example: Wrap each error element with a list item, useful when using an ordered or unordered list as the error container.
123$(".selector").validate({
wrapper: "li"
});
-
errorLabelContainerType: SelectorHide and show this container when validating.
Example: 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.
12345$("#myform").validate({
errorLabelContainer: "#messageBox",
wrapper: "li",
submitHandler: function() { alert("Submitted!") }
});
-
errorContainerType: SelectorHide and show this container when validating.
Example: 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).
123456$("#myform").validate({
errorContainer: "#messageBox1, #messageBox2",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li", debug:true,
submitHandler: function() { alert("Submitted!") }
});
-
showErrorsType: Function()A custom message display handler. 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().
Example: Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display.
12345678$(".selector").validate({
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});
The callback gets passed two arguments:
-
errorPlacement (default:
Places the error label after the invalid element
)Type: Function()Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.Example: Use a table layout for the form, placing error messags in the next cell after the input.
12345$("#myform").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
}
});
The callback gets passed two arguments:
-
successIf 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) and the validated input (as a DOM element). The label can be used to add a text like “ok!”.
Example: Add a class “valid” to valid elements, styled via CSS.
1234$("#myform").validate({
success: "valid",
submitHandler: function() { alert("Submitted!") }
});
Example: Add a class “valid” to valid elements, styled via CSS, and add the text “Ok!”.
123456$("#myform").validate({
success: function(label) {
label.addClass("valid").text("Ok!")
},
submitHandler: function() { alert("Submitted!") }
});
The callback gets passed two arguments:
-
highlight (default:
Adds errorClass (see the option) to the element
)Type: Function()How to highlight invalid fields. Override to decide which fields and how to highlight.Example: Highlights an invalid element by fading it out and in again.
1234567$(".selector").validate({
highlight: function(element, errorClass) {
$(element).fadeOut(function() {
$(element).fadeIn();
});
}
});
Example: Adds the error class to both the invalid element and it’s label
123456789101112$(".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);
}
});
The callback gets passed three arguments:
-
unhighlight (default:
Removes the errorClass
)Type: Function()Called to revert changes made by option highlight, same arguments as highlight. -
ignoreTitle (default:
false
)Type: BooleanSet to skip reading messages from the title attribute, helps to avoid issues with Google Toolbar; default is false for compability, the message-from-title is likely to be completely removed in a future release.Example: Configure the plugin to ignore title attributes on validated elements when looking for messages.
123$(".selector").validate({
ignoreTitle: true
});
-
-
Use the debug option to ease setting up validation rules, it always prevents the default submit, even when script errors occur.
Use submitHandler to implement your own form submit, eg. via Ajax. Use invalidHandler to react when an invalid form is submitted.
Use rules and messages to specify which elements to validate, and how. See rules() for more details about specifying validation rules.
Use errorClass, errorElement, wrapper, errorLabelContainer, errorContainer, showErrors, success, errorPlacement, highlight, unhighlight, and ignoreTitle to control how invalid elements and error messages are displayed.
相关推荐
在网页开发中,jQuery Validate 是一个非常常用的验证插件,用于对用户输入的数据进行校验,确保数据的有效性和完整性。这个插件可以帮助开发者创建复杂的表单验证规则,提高用户体验,减少服务器端的压力。结合 ...
**jQuery Validate 1.7 插件详解** jQuery Validate 是一款功能强大的JavaScript验证插件,主要用于前端表单验证。在1.7版本中,它继续提供了丰富的验证规则和灵活的自定义选项,使得开发者能够轻松地对用户输入...
jQuery Validate插件的强大之处在于其灵活的配置选项和丰富的验证规则,这使得开发者可以根据实际需求定制出高度可配置和个性化的表单验证方案。无论是初学者还是经验丰富的开发者,都能从中受益匪浅。
- **validate()的可选项**:`validate()` 函数接受一个配置对象,其中包含各种选项,如 `debug` 用于开启调试模式,显示验证过程中的详细信息。 ### 第三章 自定义 jQuery-validate 的验证行为 自定义验证行为主要...
jQuery Validate简化了客户端验证的复杂性,提供了丰富的选项和灵活的扩展性,是开发高效、用户体验良好的表单应用的理想工具。通过合理配置和使用,开发者可以创建出安全、易用的Web表单,同时减少服务器端的负担,...
以上四个内置验证方法是jQuery验证框架中最常用的几种验证手段,它们为开发者提供了极大的便利性和灵活性,使得实现复杂的前端表单验证变得更加简单和高效。通过合理的组合使用这些方法,可以有效地提高用户体验并...
该资源包是一个集成开发环境下的项目模板,主要涵盖了jQuery Validate、Spring 3.0、Struts 2.18和Hibernate 3这四个关键组件,它们是Java Web开发中的常用框架和技术。以下将分别对这些技术进行详细阐述。 **...
### jQuery Validate API 知识点详解 #### 一、概述 `jQuery Validate` 是 `jQuery` 的一个插件,用于简化 HTML 表单验证过程。它提供了丰富的验证规则和自定义选项,使得开发者能够轻松地实现客户端表单验证功能...
以下是 `jQuery Validate` API 的详细说明,以及一些常用验证方法的介绍。 ### 主要方法 1. **validate(options)**: 这是初始化验证的主方法,传入一个配置对象 `options`,可以设置各种验证规则、消息和行为。...
### jQuery Validate 插件详解 #### 一、插件简介 **jQuery Validate** 是一...以上介绍了 jQuery Validate 的核心功能和常用配置,通过灵活运用这些内置规则和自定义选项,可以有效地提高前端数据验证的质量和效率。
jQuery的表单校验插件`validate`是前端开发中常用的一个工具,它极大地简化了对HTML表单数据的验证过程。这个插件基于流行的JavaScript库jQuery构建,为开发者提供了丰富的选项和方法来定制表单验证规则,确保用户...
以下是一些常用选项的详细介绍: 1. **debug**(布尔值,默认:`false`) - **说明**:启用调试模式。如果设置为 `true`,则表单不会提交,并且会在浏览器控制台显示验证失败的信息。这对于调试非常有用。 - **...
为了更全面地理解jQuery Validate插件,接下来将详细介绍它的一些核心参数、常用的自定义验证规则以及如何自定义验证方法。 首先,我们来了解jQuery Validate插件的相关参数。插件提供了一套默认的验证规则和错误...
本资源集合主要关注jQuery的几个常用插件,包括jQuery UI、validate和datepicker,这些插件在实际项目中非常实用,能为网页增添丰富的交互性和功能。 1. **jQuery UI**:这是一个扩展jQuery功能的组件库,提供了...
jQuery Validate是jQuery的一个插件,广泛用于前端开发中的表单验证。它能够简化表单验证过程,提供简洁的API,易于使用和自定义。在使用jQuery Validate时,有几个常见方法和一些需要注意的问题,这些问题如果处理...
jQuery Validate 提供了一系列内置验证规则,这些规则涵盖了大部分常用场景的需求,如必填项验证、长度限制、数值范围验证等。以下是一些常见的内置验证规则: 1. **required**: 验证字段是否为空。 - 示例:`...
【jQuery 常用知识点】 jQuery 是一个广泛使用的 JavaScript 库,它简化了 DOM 操作、事件处理、动画效果和Ajax交互。以下是一些 jQuery 的核心知识点: **1. jQuery 下载** jQuery 可在官方网站...
jQuery验证控件是前端开发中常用的一种工具,它极大地简化了网页表单数据验证的过程,让开发者能够轻松实现对用户输入的实时检查。无论是静态HTML页面还是动态语言如PHP、ASP.NET、Java等构建的网站,都可以无缝集成...
以下是一些常用的jQuery插件及其功能的详细说明: 1. **jQuery UI**:这是官方提供的一个UI组件库,包含了大量的交互元素和视觉效果,如对话框、拖放、日期选择器等。尽管功能丰富,但根据实际需求,开发者通常只...