Details about the jQuery Form Verification plug-in validate and jqueryvalidate

Source: Internet
Author: User
Tags valid email address

Details about the jQuery Form Verification plug-in validate and jqueryvalidate

The validate plug-in is a jquery-based form verification plug-in. There are many common verification methods that we can call directly. Let's take a look at them.

Example: html code

<! DOCTYPE html> 

The messages_cn.js file is as follows:

JQuery. extend (jQuery. validator. messages, {required: "required field", remote: "correct this field", email: "enter an email in the correct format", url: "enter a valid URL", date: "enter a valid date", dateISO: "enter a valid date (ISO ). ", number:" enter a valid number ", digits:" Only an integer can be entered ", creditcard:" enter a valid credit card number ", please: "Enter the same value again", accept: "enter a string with a valid suffix", maxlength: jQuery. validator. format ("enter a string with a maximum length of {0}"), minlength: jQuery. validator. format ("enter a string with at least {0} length"), rangelength: jQuery. validator. format ("enter a string between {0} and {1}"), range: jQuery. validator. format ("enter a value between {0} and {1}"), max: jQuery. validator. format ("enter a maximum value of {0}"), min: jQuery. validator. format ("enter a minimum value of {0 ")});

Detailed description of validator plug-in

Mainly divided into several parts

Jquery. validate basic usage
Jquery. validate API description
Jquery. validate custom
Jquery. validate common Verification Code

Document address of jquery. validate plug-in

Http://docs.jquery.com/Plugins/Validation

Jquery. validate plug-in Home Page

Http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Demo provided on the jquery. validate plug-in Homepage

Http://jquery.bassistance.de/validate/demo/

Verification rules

The following are the default verification rules and can also be customized.

(1) required: required field for true
(2) remote: "check. php" uses ajax to call check. php to verify the input value.
(3) email: true: You must enter an email in the correct format.
(4) url: true must enter the url in the correct format
(5) date: true must be a date in the correct format
(6) dateISO: true: the date (ISO) in the correct format must be entered. For example, 2009-06-23,1998/01/22: only the format is verified and the validity is not verified.
(7) number: true: a valid number (negative number, decimal number) must be entered)
(8) digits: true must be an integer.
(9) creditcard: a valid credit card number must be entered.
(10) must to: "# field" the input value must be the same as # field
(11) accept: enter a string with a valid suffix (the suffix of the uploaded file)
(12) maxlength: A string with a maximum length of 5 characters)
(13) minlength: 10 string with a minimum input length of 10 (one character for Chinese characters)
(14) rangelength: [5, 10] The input length must be a string between 5 and 10. ") (a Chinese character is a single character)
(15) range: [5, 10] The input value must be between 5 and 10.
(16) max: 5 input value cannot be greater than 5
(17) min: 10 input value cannot be less than 10

Verification prompt

The following is the default verification prompt. The official website provides a Simplified Chinese version Verification prompt for downloading, or you can use jQuery. extend (jQuery. validator. messages custom error message. You can unify the verification text of a website into a single file.

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).",number: "Please enter a valid number.",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}.")

Usage

1:

Use the default verification rules in the control, for example:

Email (required)

<input id="email" class="required email" value="email@" />

2:

You can customize verification rules in the control, for example:

Custom (required, [3, 5])

<Input id = "complex" value = "hi" class = "{required: true, minlength: 3, maxlength: 5, messages: {required: 'Why don't you enter a text? ', minlength:' too few inputs ', maxlength: 'What are so many inputs'} "/>

3:

Using javascript custom verification rules, the following javascript custom two rules, password and confirm_password

$ (). Ready (function () {$ ("# form2 "). validate ({rules: {password: {required: true, minlength: 5}, confirm_password: {required: true, minlength: 5, failed to: "# password"}, messages: {password: {required: "No password entered", minlength: jQuery. format ("the password cannot be less than {0} characters")}, confirm_password: {required: "No Password confirmed", minlength: "The password cannot be less than {0} characters ", failed to: "inconsistent passwords entered twice "}}});});

In addition to true/false, required can also use expressions or functions, such

$ ("# Form2"). validate ({rules: {funcvalidate: {required: function () {return $ ("# password"). val ()! = "" ;}}, Messages: {funcvalidate: {required: "required if a password exists "}}});

Html

Password <input id = "password" name = "password" type = "password"/> confirm the password <input id = "confirm_password" name = "confirm_password" type = "password "/> Condition Verification <input id = "funcvalidate" name = "funcvalidate" value = ""/>

4:

Use meta to customize verification information

Set meta with JS first

$("#form3").validate({ meta: "validate" }); 

Html

Email <input class = "{validate: {required: true, email: true, messages: {required: 'input email address', email: 'The email address you entered is not valid '}}} "/>

5:

You can use meta to write verification rules in custom tags, such as validate.

Set meta in JS

$().ready(function() {$.metadata.setType("attr", "validate");$("#form1").validate();});

Html

Email

<Input id = "email" name = "email" validate = "{required: true, email: true, messages: {required: 'input email address', email: 'The email address you entered is not valid '} "/>

6:

Custom verification rules

For complex verification, you can use jQuery. validator. addMethod to add custom verification rules.

The additional-methods.js provided by the official website contains some common verification methods, such as lettersonly, ziprange, nowhitespace, etc.

Example

// Verify jQuery. validator. addMethod ("userName", function (value, element) {return this. optional (element) |/^ [\ u0391-\ uFFE5 \ w] + $ /. test (value) ;}, "the user name can only contain Chinese characters, English letters, numbers, and underscores"); // then you can use this rule $ ("# form1 "). validate ({// verification rule rules: {userName: {required: true, userName: true, rangelength: [5, 10]},/* set error message */messages: {userName: {required: "Enter the user name", rangelength: "The user name must be between 5-10 characters "}},});

7:

The verification methods for radio, checkbox, and select are similar.

Radio Verification

Gender

<Span> male <input type = "radio" id = "gender_male" value = "m" name = "gender" class = "{required: true} "/> <br/> female <input type =" radio "id =" gender_female "value =" f "name =" gender "/> </span>

Checkbox Verification

Select at least two items

<Span> Option 1 <input type = "checkbox" id = "check_1" value = "1" name = "checkGroup" class = "{required: true, minlength: 2, messages: {required: 'optional ', minlength: 'select at least two items'} "/> <br/> Option 2 <input type =" checkbox "id =" check_2 "value =" 2 "name =" checkGroup "/> <br/> Option 3 <input type = "checkbox" id = "check_3" value = "3" name = "checkGroup"/> <br/> </span>

Select Verification

Drop-down list

<span><select id="selectbox" name="selectbox" class="{required:true}"><option value=""></option><option value="1">1</option><option value="2">2</option><option value="3">3</option></select></span>

8:

Ajax Verification

Remote can be used for Ajax Verification

Remote: {url: "url", // url type: "post", // transmission method dataType: "json", // data format data: {// username: function () {return $ ("# username "). val ();}}}

Plugin methods

Name Type

Validate (options) Returns: Validator

Verify the selected FORM

Valid () Returns: Boolean

Check whether verification is passed

Rules () Returns: Options

Verification rules for returned Elements

Rules ("add", rules) Returns: Options

Add verification rules

Rules ("remove", rules) Returns: Options

Delete verification rules

RemoveAttrs (attributes) Returns: Options

Delete special attributes and return them

Custom selectors
Name Type

: Blank Returns: Array <Element>
Filter with no value

: Filled Returns: Array <Element>
Filter with values

: Unchecked Returns: Array <Element>
Filter of unselected Elements
Utilities

Name Type

JQuery. format (template, argument, argumentN...) Returns: String
Replace {n} in the template with parameters }.
Validator

The validate method returns A Validator object. There are many methods that allow you to use the content that triggers the verification program or change the form.

Below is a list of commonly used.

Form () Returns: Boolean
Whether the result of form verification is successful or not

Element (element) Returns: Boolean
Verify whether a single element is successful or failed

ResetForm () Returns: undefined
Restore the previously verified FORM to the original status before verification

ShowErrors (errors) Returns: undefined
Display specific error messages
Built-in Validation methods

Name Type

SetDefaults (defaults) Returns: undefined
Change default settings

AddMethod (name, method, message) Returns: undefined
Add a new verification method. The name, a JAVASCRIPT method, and a default information must be included.

AddClassRules (name, rules) Returns: undefined
Added the combined verification type.

AddClassRules (rules) Returns: undefined
Added the combined verification type.
Built-in Validation methods

Name Type

Required () Returns: Boolean
Required verification element

Required (dependency-expression) Returns: Boolean
The required element depends on the result of the expression.

Required (dependency-callback) Returns: Boolean
The required element depends on the result of the callback function.

Remote (url) Returns: Boolean
Request Remote verification. A url is usually a remote call method.

Minlength (length) Returns: Boolean
Set minimum length

Maxlength (length) Returns: Boolean
Set the maximum length

Rangelength (range) Returns: Boolean
Set a length range of [min, max]

Min (value) Returns: Boolean
Set the minimum value.

Max (value) Returns: Boolean
Set the maximum value.

Range (range) Returns: Boolean
Set the value range

Email () Returns: Boolean
Verify email format

Url () Returns: Boolean
Verify the connection format

Date () Returns: Boolean
Verification Date Format (similar to the format of 30/30/2008. if the date is not verified, only the format is verified)

DateISO () Returns: Boolean
Date Format of ISO type developed

DateDE () Returns: Boolean
Verify the German Date Format (292.164.1994 or 1.1.2006)

Number () Returns: Boolean
Verify the decimal number (including decimal digits)

NumberDE () Returns: Boolean
Makes the element require a decimal number with german format.

Digits () Returns: Boolean
Verification integer

Creditcard () Returns: Boolean
Verify credit card number

Accept (extension) Returns: Boolean
Verify strings with the same suffix

Failed to (other) Returns: Boolean
Verify that the content of the two input boxes is the same

Customize the validation behavior of jquery-validate

1: custom form submission

Set submitHandler to customize the form submission action

$ (". Selector"). validate ({submitHandler: function (form) {alert ("verified ");}});

To submit a form, call
Form. submit (); or $ (form). ajaxSubmit ();

2: debugging mode

Set debug to true, and the form is not submitted. Check only to facilitate debugging.

$(".selector").validate({debug: true})

3: Set the default value of validate

You can use setDefaults to set the default value of validate. For example, all form verification tasks are performed in debug mode by default.

$.validator.setDefaults({debug: true})

4: some elements are not verified.

You can set the ignore attribute to ignore some elements that are not verified.

$(".selector").validate({ignore: "ignore"})

5: verification time

Jquery. validate allows you to easily set when verification actions are triggered.

Onsubmit: whether to verify when submitting

$(".selector").validate({onsubmit: false})

Onfocusout: verification when the focus is lost (except for checkboxes/radio)

$(".selector").validate({onfocusout: false})

Onkeyup: verification during keyup

$(".selector").validate({onkeyup: false})

Onclick: Verify when checkboxes and radio are clicked.

$(".selector").validate({onclick: false})

6. Rewrite verification rules and verification prompt information.

// Rewrite the verification prompt information of max $. validator. messages. max = jQuery. format ("Your totals musn't exceed {0 }! "); // Override equal method $. validator. methods. equal = function (value, element, param) {return value = param ;};

7: Does focusInvalid focus on the last action or the last error?

$(".selector").validate({focusInvalid: false})

8: focusCleanup

If this attribute is set to True, when the control obtains the focus, it removes the wrong class definition and hides the error information to avoid using it with focusInvalid.

$(".selector").validate({focusCleanup: true})

9: meta

Set meta to encapsulate verification rules

$(".selector").validate({meta: "validate",})<script type="text/javascript"></script>

Custom display of error messages

By default, the label element is used to display the verification prompt information, and css class is added. Through css, you can easily set the error control and display mode of error information.

/* Input control verification error */form input. error {border: solid 1px red;}/* verification error message */form label. error {width: 200px; margin-left: 10px; color: Red ;}

To customize the display mode, you can modify the default display mode of jquery. validate.

The label is used by default to Display error messages, which can be modified through the errorElement attribute.
ErrorElement: html tag of the error message

$(".selector").validateerrorElement: "em"})

You can use other elements to wrap a layer in the error message.
Wrapper: the html Tag is encapsulated in the outer layer of the error message.

$(".selector").validate({wrapper: "li"})

The default css class for verification errors is error, which can be modified through errorClass.
ErrorClass: the css class used for error Verification

$(".selector").validate({errorClass: "invalid"})

Also customize the action when the verification is successful
Success: If the value is a string, it is treated as a css class. If it is a function, it is executed.

$(".selector").validate({success: "valid"})

Or

success: function(label) {label.html(" ").addClass("checked");}

You can also unify the error messages to a container for display.
ErrorLabelContainer: Unified error messages to a container for display.

$("#myform").validate({errorLabelContainer: "#messageBox"})

By default, error messages are placed after verification elements. You can customize the display location of error messages.

$(".selector").validate({errorPlacement: function(error, element) {error.appendTo( element.parent("td").next("td") );}})

Further, you can define a group to unify the error information in several places and use the error Placement to control where the error information is stored.
Groups: defines a group.

$(".selector").validate({groups: {username: "fname lname"},errorPlacement: function(error, element) {if (element.attr("name") == "fname" || element.attr("name") == "lname" )error.insertAfter("#lastname");elseerror.insertAfter(element);}})

Highlight

Highlight: highlighted. By default, errorClass is added.
Unhighlight: corresponds to highlight and is highlighted in reverse mode.

$(".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);}});

Or you can customize the error display.
ShowErrors: The display handle is incorrect.

$ (". Selector "). validate ({showErrors: function (errorMap, errorList) {$ ("# summary" ).html ("Your form contains" + this. numberOfInvalids () + "errors, see details below. "); this. defaultShowErrors () ;}}) <script type = "text/javascript"> </script> // verify jQuery by phone number. validator. addMethod ("mobile", function (value, element) {var length = value. length; var mobile =/^ (13 [0-9] {1}) | (15 [0-9] {1}) + \ d {8 }) $/return this. opti Onal (element) | (length = 11 & mobile. test (value) ;}, "Incorrect Mobile Phone Number Format"); // call number verification jQuery. validator. addMethod ("phone", function (value, element) {var tel =/^ (0 [0-9] {2, 3 }\-)? ([2-9] [0-9] {6, 7}) + (\-[0-9] {1, 4 })? $/; Return this. optional (element) | (tel. test (value) ;}, "Incorrect Phone Number Format"); // zip code verification jQuery. validator. addMethod ("zipCode", function (value, element) {var tel =/^ [0-9] {6} $/; return this. optional (element) | (tel. test (value) ;}, "Incorrect zip code format"); // verify jQuery with a QQ number. validator. addMethod ("qq", function (value, element) {var tel =/^ [1-9] \ d {4, 9} $/; return this. optional (element) | (tel. test (value) ;}, "Incorrect QQ number format"); // ip address Verify jQuery. validator. addMethod ("ip", function (value, element) {var ip =/^ (? :(?: 25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) \.) {3 }(?: 25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) $/; Return this. optional (element) | (ip. test (value) & (RegExp. $1 <256 & RegExp. $2 <256 & RegExp. $3 <256 & RegExp. $4 <256) ;}, "Incorrect IP address format"); // verify jQuery with letters and numbers. validator. addMethod ("chrnum", function (value, element) {var chrnum =/^ ([a-zA-Z0-9] +) $/; return this. optional (element) | (chrnum. test (value);}, "only numbers and letters (character A-Z, a-z, 0-9)"); // verify jQuery in Chinese. validator. addMethod ("chinese", function (value, element) {var chinese =/^ [\ u4e00-\ u9fa5] + $/; return this. optional (element) | (chinese. test (value) ;}, "only Chinese characters can be entered"); // drop-down box verification $. validator. addMethod ("selectNone", function (value, element) {return value = "select" ;}, "must select one"); // verify the length of the byte in 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 ("make sure that the input value is between {0}-{1} bytes (one text is counted as two bytes )"));

Articles you may be interested in:
  • JQuery Validate verification, validation rules written in a specific instance in the control
  • Jquery validate custom verification method description date Verification
  • Use the jquery. validate custom method to implement logic verification of "Enter at least one mobile phone number or fixed phone number"
  • JQuery verification plug-in Validate details
  • Form Verification Based on Bootstrap + jQuery. validate
  • Jquery uses validate in combination with CSS to implement beautiful Verification
  • The jquery validate and jquery form plug-ins are combined to implement AJAX submission after verification form
  • Jquery. validate custom verification method and validate related parameters

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.