Examples of jquery form verification plug-in Validate_jquery

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

The Validate plug-in is a jquery based form verification plug-in. There are many common methods of verification that we can call directly, specifically we look at together.

example, HTML code

<! DOCTYPE html>  

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 the 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 valid 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 (" 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: "To fix this field.", Email: "Please ente R 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:" To enter the same value again. ", Accept:" Please enter a value with a valid ex Tension. ", MaxLength: $.validator.format (" Please enter no more than {0} characters. "), MinLength: $.validator.format (" Please enter in least {0} characters. "), Rangelength: $.validator.format (" Please enter a value between {0} and {1} charact  ERs 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 enter 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: "No password is filled in",
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 input password inconsistent"
}
}
});
});

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

$ ("#form2"). Validate ({The
rules: {
funcvalidate: {
required:function () {return $ ("#password"). Val ()!= " ";}}}
,
messages: {
funcvalidate: {
Required:" Must fill in the case of Password}}}
);

Html

Password <input id= "password" name= "password" type= "password"/>
confirmation password <input id= "Confirm_password" Confirm_password "type=" password "/>
conditional validation <input id=" funcvalidate "name=" "Funcvalidate" "value="

4:

Use meta custom validation information

First use JS to set meta

 
 

Html

Email<input class= "{validate:{required:true, Email:true,
messages:{required: ' Enter email address ', email: ' You are not entering a valid mail 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 mail 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);
}, "User name can only include Chinese characters, English letters, numbers, and underscores"); 
You can then use this rule
$ ("#form1"). Validate ({
//validation rules
: {
userName: {
required:true,
Username:true,
rangelength: [5,10]
}
},/
* SET error message * *
messages: {
userName: {
Required: "Please fill in username",
rangelength: "username 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>
options 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/>
options 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",//Send way
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

Rewrite Max's validation prompt
$.validator.messages.max = jquery.format ("Your totals Musn ' t exceed {0}!");
Rewrite 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.nu
Mberofinvalids () + "errors, the details below.");
This.defaultshowerrors (); }) <script type= "Text/javascript" ></script>//Mobile 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 (E Lement) | |
(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 authentication 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"); Letter and number validation jQuery.validator.addMethod ("Chrnum", function (value, Element) {var chrnum =/^ ([a-za-z0-9]+) $/; Optional (Element) | |
(Chrnum.test (value));
"Only numbers and letters (characters A-Z, A-Z, 0-9)" can be entered; Verification JQuery.validator.addMethod in Chinese ("Chinese", function (value, Element) {var Chinese =/^[\u4e00-\u9fa5]+$/; . Optional (Element) | |
(Chinese.test (value));
"Can only be entered in Chinese");
The dropdown box verifies $.validator.addmethod ("Selectnone", function (value, Element) {return value = = "Please select";}, "must select one"); 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.