jquery Validate Form Verification plug-in usage examples and detailed

Source: Internet
Author: User
Tags button type class definition extend valid valid email address wrapper zip

example, HTML code

<! DOCTYPE html>
<include file= "Common/header"/>
<meta charset= "Utf-8" >
<script src= "/jquery.min.js" ></script>
<body>
<form class= "form-horizontal" id= "form" onsubmit= "return false;" >
<input type= "text" name= "Password_old" class= "Form-control required" id= "Password_old" maxlength= ">"
<input type= "Password" name= "Pay_password" class= "Form-control required" id= "Pay_password" >
<input type= "Password" name= "password_repeat" class= "Form-control required" id= "Password_repeat" >
<button type= "Submit" id= "Submit" class= "btn btn-success btn-padding-lr-30 margin-right-15" > OK </button>
</form>
</body>
<!------------------------------------------------------------------------->

<script src= "Jquery.validate.min.js" ></script>
<script src= "Messages_cn.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (function () {
Submit
$ (' #submit '). Click (function () {

var Pay_password = $ (' #pay_password '). Val ();


var password_repeat = $ (' #password_Repeat '). Val ();


var password_old = $ (' #password_old '). Val ();





var data = {


' Pay_password ':p Ay_password,


' Password_repeat ':p assword_repeat,


' Password_old ':p assword_old


};





Console.info (data);





var v = $ (' #form '). Validate ({


Rules: {


Pay_password: {


Required:true,


Minlength:6,


Ismypassword:true


},


Password_repeat: {


Required:true,


Minlength:6,


Ismypassword:true


},


Password_old: {


Required:true,


Minlength:6,


}


},

Messages: {


Pay_password: {


Required: "Please enter the password",


MinLength: "Character length cannot be less than 6 characters",


Ismypassword: "The password must consist of numbers, English letters and special characters (!,. @#$%^&amp;*?_~)."


},


Password_repeat: {


Required: "Please enter the password",


MinLength: "Character length cannot be less than 6 characters",


Ismypassword: "The password must consist of numbers, English letters and special characters (!,. @#$%^&amp;*?_~)."


},


Password_old: {


Required: "Please enter the password",


MinLength: "Character length cannot be less than 6 characters",


},


}


});





if (Pay_password!= password_repeat) {


Alert ("Password inconsistent, please re-enter the confirmation!") "); return false;


}


//---------------------------------


if (!v.form ()) return false;

   $.ajax ({
    url: ' {: U (' MERCHANT/AJAX_PW ')} ',
     data:data,
    beforesend:function () {
     
  &NBSP;&NBSP;&NBSP},
    success:function (res) {  
       if (res = = 1) {
       alert ("Successful password modification");
    &NBSP;&NBSP;&NBSP;&NBSP}
      if (res = = 0) {
        alert ("Two times password, no modification");
       } 
      if (res!= 0 & & Res!= 1) {
       alert (res);
       &NBSP;}&NBSP
    }
   
   //------------------------
});

})
</script>

Messages_cn.js files are as follows

Jquery.extend (JQuery.validator.messages, {
Required: "Required fields",
Remote: "Please fix this field",
Email: "Please enter the correct format email",
URL: "Please enter a valid URL",
Date: "Please enter a valid date",
Dateiso: "Please enter a valid date (ISO).",
Number: "Please enter legal numbers",
Digits: "Only integers can be entered",
CreditCard: "Please enter a valid credit card number",
Equalto: "Please enter the same value again",
Accept: "Please enter a string with a legal suffix name",
Maxlength:jQuery.validator.format ("Please enter a string with a maximum length of {0}"),
Minlength:jQuery.validator.format ("Please enter a string with a length of at least {0}"),
Rangelength:jQuery.validator.format ("Please enter a string between {0} and {1}"),
Range:jQuery.validator.format ("Please enter a value between {0} and {1}"),
Max:jQuery.validator.format ("Please enter a value of max {0}"),
Min:jQuery.validator.format ("Please enter a value of min {0}")
});


about Validator Plug-in detailed


mainly divided into several parts
Basic usage of Jquery.validate
Jquery.validate API Description
Jquery.validate Customization
Jquery.validate Common types of validation code

Download Address

Jquery.validate Plugin's document address
Http://docs.jquery.com/Plugins/Validation

Home page of the Jquery.validate plugin
http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Demo available on the Jquery.validate plugin home page
http://jquery.bassistance.de/validate/demo/

Validation rules

The following are the default checksum rules, or you can customize the rules

(1) Required:true must be lost field

(2) Remote: "check.php" use Ajax method to invoke check.php validate input value

(3) Email:true must enter the correct format email

(4) Url:true must enter the URL in the correct format

(5) Date:true must enter a date in the correct format

(6) Dateiso:true must enter the correct format of the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, do not verify the validity

(7) Number:true must enter a valid number (negative, decimal)

(8) Digits:true must enter an integer

(9) CreditCard: Must enter the legal credit card number

(a) Equalto: "#field" input value must be the same as #field

(one) Accept: Enter a string with a valid suffix name (the suffix of the uploaded file)

(Maxlength:5) A string with a maximum of 5 input length (Chinese characters are counted as one character)

(Minlength:10) A string with a minimum input length of 10 (Chinese characters are counted as one character)

(rangelength:[5,10] Enter a string that must be between 5 and 10) (Chinese characters are counted as one character)

() range:[5,10] The input value must be between 5 and 10

() Max:5 input value cannot be greater than 5

(min:10) input value cannot be less than 10

Validation Tips

The following is the default validation prompts, the official website has Simplified Chinese version of the verification prompts download, or through Jquery.extend (jQuery.validator.messages custom error message, can be the site's validation hint text unified into a file.

Required: "This field is required.",

Remote: "Please fix this field.",

Email: "Please enter a valid e-mail 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 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}.")

How to use

1:

Use default validation rules in controls, examples:

e-mail (required)

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

2:

You can customize validation rules in a control, for example:

Custom (required, [3,5])

<input id= "complex" value= "HI" class= "{required:true,minlength:3, Maxlength:5,

Messages:{required: ' Why not input a bit of text ', minlength: ' Too little input ', maxlength: ' Input so much do '} '/>

3:

With JavaScript custom validation rules, the following JS customizes two rules, password and Confirm_password

$ (). Ready (function () {

$ ("#form2"). Validate ({

Rules: {

Password: {

Required:true,

Minlength:5

},

Confirm_password: {

Required:true,

Minlength:5,

Equalto: "#password"

}

},

Messages: {

Password: {

Required: "Did not fill in the password",

Minlength:jQuery.format ("Password cannot be less than {0} characters")

},

Confirm_password: {

Required: "No confirmation password",

MinLength: "Confirm password cannot be less than {0} characters",

Equalto: "Two times the input password is inconsistent."

}

}

});

});

In addition to being set to True/false, required can also use expressions or functions, such as

$ ("#form2"). Validate ({

Rules: {

Funcvalidate: {

Required:function () {return $ ("#password"). Val ()!= "";}

}

},

Messages: {

Funcvalidate: {

Required: "Must fill in the case with password"

}

}

});

Html

Password <input id= "password" name= "password" type= "password"/>

Confirm Password <input id= "Confirm_password" name= "Confirm_password" type= "password"/>

Conditional validation <input id= "Funcvalidate" name= "funcvalidate" value= ""/>

4:

Use meta custom validation information

First use JS to set meta

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

Html

Email<input class= "{validate:{required:true, Email:true,

messages:{required: ' Input email address ', email: ' You are not entering a valid email address '}} '/>

5:

Use meta to write validation rules in a custom label, such as Validate

JS Settings meta

$ (). Ready (function () {

$.metadata.settype ("attr", "validate");

$ ("#form1"). Validate ();

});

Html

Email

<input id= "Email" name= "email"

Validate= "{required:true, Email:true, messages:{required: ' Enter email address ', email: ' You are not entering a valid email address '}} '/>

6:

Custom validation Rules

For complex validation, you can add custom validation rules through JQuery.validator.addMethod

The additional-methods.js contained in the official website contains some commonly used verification methods, such as Lettersonly,ziprange,nowhitespace

Example

Character validation

JQuery.validator.addMethod ("UserName", function (value, Element) {

return this.optional (Element) | | /^[\u0391-\uffe5\w]+$/.test (value);

"The user name can only include Chinese characters, English letters, numbers, and underscores".

And then you can use this rule.

$ ("#form1"). Validate ({

Validation rules

Rules: {

UserName: {

Required:true,

Username:true,

Rangelength: [5,10]

}

},

/* SET error message * *

Messages: {

UserName: {

Required: "Please fill in User name",

Rangelength: "User name must be between 5-10 characters"

}

},

});

7:

Radio, checkbox, select are validated in a similar way

Verification of Radio

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>

Verification of CheckBox

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: ' must choose ', MinLength: ' Select at least 2 '}} '/><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>

Validation of Select

Drop down box

<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 validation

Remote can be used for AJAX validation

Remote: {

URL: "url",//url address

Type: "POST",//mode of delivery

DataType: "JSON",//Data format: {//data to be passed

Username:function () {

Return $ ("#username"). Val ();

}}

}

Plugin methods

Name Type

Validate (options) Returns:validator

Verify the selected form

Valid () Returns:boolean

Check to see if validation passes

Rules () returns:options

Returns the validation rule for an element

Rules ("Add", rules) returns:options

Adding validation rules

Rules ("Remove", rules) returns:options

Delete validation rules

Removeattrs (attributes) returns:options

Delete Special properties and return them

Custom Selectors

Name Type

: Blank Returns:array <element >

Filter with no value

: Filled Returns:array <element >

A filter with a value

: Unchecked Returns:array <element >

Filters for elements that are not selected

Utilities

Name Type

Jquery.format (template, argument, argumentn ...) Returns:string

Replace {n} in the template with a parameter.

Validator

The Validate method returns a validator object, which has a number of methods that allow you to use the trigger checker or change the contents of the form.

The following is a list of commonly used.

Form () Returns:boolean

Verify that the form returns success or failure

Element (Element) Returns:boolean

To verify that a single element succeeds or fails

Resetform () returns:undefined

Restores the previously validated form to its original state before validation

ShowErrors (Errors) returns:undefined

Display a specific error message

Built-in Validation methods

Name Type

SetDefaults (defaults) returns:undefined

Change the default settings

Addmethod (name, method, message) returns:undefined

Add a new authentication method. Must include the name, a JavaScript method, and a default message

Addclassrules (name, rules) returns:undefined

Add Combination validation type

Addclassrules (Rules) returns:undefined

Add Combination validation type

Built-in Validation methods

Name Type

Required () Returns:boolean

Required validation Elements

Required (dependency-expression) Returns:boolean

Required elements depend on the result of an expression.

Required (Dependency-callback) Returns:boolean

Required elements depend on the result of the callback function.

Remote (URL) returns:boolean

Request a remote checksum. A URL is usually a remote calling method

MinLength (length) Returns:boolean

Set Minimum Length

MaxLength (length) Returns:boolean

Set Maximum length

Rangelength (range) Returns:boolean

Set a length range [Min,max]

Min (value) Returns:boolean

Set the minimum value.

Max (value) Returns:boolean

Set the maximum value.

Range (range) Returns:boolean

Set the range of values

Email () Returns:boolean

Verify e-mail format

URL () Returns:boolean

Verifying connection formats

Date () Returns:boolean

Validate date format (similar to 30/30/2008 format, do not validate date accuracy only validate format)

Dateiso () Returns:boolean

Develop an ISO type of date format

Datede () Returns:boolean

Verify the German date format (29.04.1994 or 1.1.2006)

Number () Returns:boolean

Verify decimal digits (including decimals)

Numberde () Returns:boolean

Makes the element require a decimal number with German format.

Digits () Returns:boolean

validating integers

CreditCard () Returns:boolean

Verify credit card number

Accept (extension) Returns:boolean

A string that validates the same suffix name

Equalto (Other) Returns:boolean

Verify that the contents of the two input boxes are the same

Validation behavior for custom Jquery-validate

1: Customize form submission

Set Submithandler to customize form submission actions

$ (". Selector"). Validate ({

Submithandler:function (form) {alert ("validation passed");}

});

If you need to submit a form, you can call

Form.submit (); or $ (form). Ajaxsubmit ();

2: Debug mode

Set Debug to True, the form will not be submitted, only check for easy debugging

$ (". Selector"). Validate ({

Debug:true

})

3: Set the default value for validate

Use SetDefaults to set default values for validate, such as default all form validation is done in debug mode

$.validator.setdefaults ({

Debug:true

})

4: Some elements are not validated

Set the Ignore property to ignore certain elements that are not validated

$ (". Selector"). Validate ({

Ignore: "Ignore"

})

5: Time to verify

Jquery.validate can easily set when the validation action is triggered

OnSubmit: Whether to validate at commit

$ (". Selector"). Validate ({

Onsubmit:false

})

Onfocusout: Validation when focus is lost (except Checkboxes/radio)

$ (". Selector"). Validate ({

Onfocusout:false

})

OnKeyUp: Validating at KeyUp

$ (". Selector"). Validate ({

Onkeyup:false

})

OnClick: When checkboxes, Radio click to verify.

$ (". Selector"). Validate ({

Onclick:false

})

6: Overriding validation rules and validation prompts

Overriding the validation hints for max

$.validator.messages.max = Jquery.format ("Your totals Musn ' t exceed {0}!");

Overriding the Equal method

$.validator.methods.equal = function (value, element, param) {

return value = = param;

};

7:focusinvalid whether to focus on the last action or the most recent error

$ (". Selector"). Validate ({

Focusinvalid:false

})

8:focuscleanup

If the property is set to True, the class definition of the error is removed, the error message is hidden, and the focusinvalid is avoided when the control obtains the focus.

$ (". Selector"). Validate ({

Focuscleanup:true

})

9:meta

Set up meta to encapsulate validation rules

$ (". Selector"). Validate ({

Meta: "Validate",

})

<script type= "Text/javascript" ></script>

How custom error messages are displayed

By default, the validation prompt is displayed with a LABEL element, and CSS class is added, which makes it easy to set error controls and display the error messages by using CSS.

/* Input Control validation Error *

Form Input.error {border:solid 1px red;}

/* Validation error message * *

form label.error{width:200px;margin-left:10px; color:red;}

If you want to customize the display style, you can modify the default display for Jquery.validate

The default is to display the error message with the label, which can be modified by the Errorelement property

Errorelement: HTML tag for error messages

$ (". Selector"). Validate

Errorelement: "em"

})

You can wrap a layer of other elements in an error message.

Wrapper: The outer layer of the error message encapsulates the HTML tag

$ (". Selector"). Validate ({

Wrapper: "Li"

})

Validation error CSS Class default is error, through Errorclass can modify

Errorclass: CSS class used when validating an error

$ (". Selector"). Validate ({

Errorclass: "Invalid"

})

Also customize the actions when validation succeeds

Success: If the value is a string, it will be treated as a CSS class, and if it is a function, execute the function

$ (". Selector"). Validate ({

Success: "Valid"

})

Or

Success:function (label) {

Label.html (""). AddClass ("checked");

}

You can also unify the error message to a container display

Errorlabelcontainer: Unifies the error message to a container display

$ ("#myform"). Validate ({

Errorlabelcontainer: "#messageBox"

})

By default, the error message is placed behind the validation element to customize the display location of the error message

$ (". Selector"). Validate ({

Errorplacement:function (Error, Element) {

Error.appendto (Element.parent ("TD"). Next ("TD");

}

})

Further, you can define a group, place the error information in a few places in one place, and use the error placement to control where to put the error message.

Groups: Define a group

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

}

})

Highlight Display

Highlight: Highlighted, the default is to add Errorclass

Unhighlight: Corresponding to highlight, inverse highlighting

$ (". 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 completely customize the error display

ShowErrors: Get the wrong display handle

$ (". Selector"). Validate ({

Showerrors:function (Errormap, errorlist) {

$ ("#summary"). HTML ("Your form contains" + This.numberofinvalids ()

+ "errors, the details below.");

This.defaultshowerrors ();

}

})

<script type= "Text/javascript" ></script>

Mobile phone number Verification

JQuery.validator.addMethod ("mobile", function (value, Element) {

var length = Value.length;

var mobile =/^ ((13[0-9]{1}) | ( 15[0-9]{1}) +\d{8}) $/

return this.optional (Element) | | (length = = && Mobile.test (value));

}, "mobile phone number format error");

Phone 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));

}, "Phone number format error");

ZIP Code Verification

JQuery.validator.addMethod ("ZipCode", function (value, Element) {

var tel =/^[0-9]{6}$/;

return this.optional (Element) | | (Tel.test (value));

}, "ZIP code format error");

QQ Number Verification

JQuery.validator.addMethod ("QQ", function (value, Element) {

var tel =/^[1-9]\d{4,9}$/;

return this.optional (Element) | | (Tel.test (value));

}, "QQ number format error");

IP Address Verification

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 && Rege Xp.$4 < 256));

}, "IP address format error");

Verification of letters and numbers

JQuery.validator.addMethod ("Chrnum", function (value, Element) {

var chrnum =/^ ([a-za-z0-9]+) $/;

return this.optional (Element) | | (Chrnum.test (value));

"Only numbers and letters (characters A-Z, A-Z, 0-9)" can be entered;

Verification in Chinese

JQuery.validator.addMethod ("Chinese", function (value, Element) {

var Chinese =/^[\u4e00-\u9fa5]+$/;

return this.optional (Element) | | (Chinese.test (value));

"Can only be entered in Chinese");

Dropdown box Validation

$.validator.addmethod ("Selectnone", function (value, Element) {

return value = = "Please select";

"Must select an item");

byte length validation

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 the value entered is between {0}-{1} bytes (2 bytes in one)");

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.