One, optional (options)
[1] Debug type: Boolean Default: False
Note: Turn on debug mode. If true, the form will not commit and will display some error messages on the console (requires Firebug or Firebug Lite). When you want to prevent the form from submitting events by default, try to open it.
JS Code
$ (". Selector"). Validate ({
Debug:true
})
[2] Submithandler type: Callback defaults: Default (native) Form submit
Note: When the form is validated, submits the form. The callback function has a default parameter form
JS Code
$ (". Selector"). Validate ({
Submithandler:function (form) {
Do and stuff for a valid form
Form.submit ();
}
})
[3] Invalidhandler type: Callback
Description: When submitting a form that is not validated, you can handle something in the callback function. The callback function has two parameters: the first is an event object and the second is a validator (validator)
JS Code
$ (". Selector"). Validate ({
Invalidhandler:function (Form, validator) {
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 ();
}
}
})
[4] Ignore type: seletor
Note: When making a form validation, filter out the form selected by the selector. The jquery Not method (not ()) is used. Forms that are type submit and reset are always ignored.
JS Code
$ ("#myform"). Validate ({
Ignore: ". Ignore"
})
[5] Rules type: Options default: Rules are read from markup (classes, attributes, metadata)
Description: A user-defined key/value pair rule. The key is the Name property (or a set of radio/check buttons) for a form element, the value is a simple string, or an object consisting of a rule/parameter pair (Rule/parameter). Can be used in conjunction with the Class/attribute/metadata rule. Each rule can specify a dependent validation prerequisite.
JS Code
$ (". Selector"). Validate ({
Rules: {
Converted to {required:true}
Name: "Required",
Compound rule
Email: {
Required:true,
Email:true
}
}
})
[6] Messages type: Options default: The message that the validation method uses by default
Description: A user-defined key/value pair message. The key is the Name property of a form element, and the value is the message that the form element will display. The message overrides the title property of the element or the default message. The message can be a string or a callback function. The callback function must be called in the scope of the validator, the rule parameter as the first parameter of the callback function, the form element as the second parameter of the callback function, and a message of type string must be returned.
JS Code
$ (". Selector"). Validate ({
rules: {
Name: "Required",
& nbsp; Email: {
required:true,
email:true
}
},
messages: {
Name: "Please specify your name",
Email: {
Required: "We need your email address for you",
Email: "Your email address must is in the format of name@domain.com"
}
}
})
[7] groups Type: Options
Description: Specifies the error message grouping. A group consists of an arbitrary group name as a key, and a list of table cell name attributes separated by whitespace as a value. Use Errorplacement to define where the group messages are stored.
JS Code
$ ("#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
})
[8] onsubmit type: Boolean default: True
Description: Validates the form upon submission. When set to False, only other events can be validated.
JS Code
$ (". Selector"). Validate ({
Onsubmit:false
})
[9] onfocusout type: Boolean default: True
Description: Verify when focus is away (except the Radio/Check button). If nothing is entered in the form, all rules are skipped unless the form has been marked as invalid.
JS Code
$ (". Selector"). Validate ({
Onfocusout:false
})
[Ten] onkeyup type: Boolean default: True
Note: When the keyboard key is bouncing up to verify. As long as the form element is not marked as invalid, there is no response. In addition, all rules will be validated each time the keystroke is bounced.
JS Code
$ (". Selector"). Validate ({
Onkeyup:false
})
[One] onclick type: Boolean default: True
Description: Mouse Click Verify for Radio and check button.
JS Code
$ (". Selector"). Validate ({
Onclick:false
})
[[] focusinvalid type: Boolean default: True
Note: When validation is invalid, the focus jumps to the first invalid form element. When false, there is no focus response when the validation is invalid.
JS Code
$ (". Selector"). Validate ({
Focusinvalid:false
})
[[] focuscleanup type: Boolean default: False
Description: If True, removes the Errorclass on the form and hides all error messages when the form has the focus. Avoid use with Focusinvalid.
JS Code
$ (". Selector"). Validate ({
Focuscleanup:true
})
[[] Meta type: String
Note: If you want to use a different plug-in to use the metadata validation rules, you must specify the corresponding metadata object.
JS Code
$ ("#myform"). Validate ({
Meta: "Validate"
})
<input type= "text" name= "email" class= "{validate:{required:true, email:true}}"/>
[Errorclass] Type: String default: "Error"
Description: Use this set of styles to define the style of the error message.
JS Code
$ (". Selector"). Validate ({
Errorclass: "Invalid"
})
[Validclass] Type: String default: "Valid"
Description: Sets the style of the message display when validation passes.
JS Code
$ (". Selector"). Validate ({
Validclass: "Success"
})
[[] errorelement type: String default: ' label '
Description: Creates a container for error messages with HTML element types. One advantage of the default label is the ability to create meaningful connections between the error message and the invalid form by using the for attribute (one that is often used, regardless of what the form element is).
JS Code
$ (". Selector"). Validate ({
Errorelement: "em"
})
[Wrapper] Type: Boolean
Description: Surrounds the error message with a specified element. It is useful to create a list of error messages with Errorlabelcontainer.
JS Code
$ (". Selector"). Validate ({
Wrapper: "Li"
})
[[] Errorlabelcontainer type: Selector
Description: The container for the error message label.
JS Code
$ ("#myform"). Validate ({
Errorlabelcontainer: "#messageBox",
Wrapper: "Li"
})
[Errorcontainer] Type: Selector
Description: The container for the error message.
JS Code
$ ("#myform"). Validate ({
errorcontainer: "#messageBox1, #messageBox2 ″,
Errorlabelcontainer: "#messageBox1 ul",
wrapper: "Li", debug:true,
Submithandler: function () {alert ("submitted!")}
})
[20] showerrors type:callback default: None, built-in display message
Description: A handle to the custom message display. The callback function has two parameters, the first is Errormap, and the second parameter is errorlist, which is called in the context of the validator object. The parameters contain only those form elements that have been onblur/onkeyup validated, or they may be individual elements. In addition, you can use This.defaultshowerrors () to trigger the default behavior.
JS Code
$ (". Selector"). Validate ({
showerrors:function (Errormap, errorlist) {
& nbsp; $ ("#summary"). HTML ("Your form contains"
+ this.numberofinvalids ()
+ "errors, the details below.");
this.defaultshowerrors ();
}
})
[21] errorplacement Type:callback default: Label immediately following invalid form
Description: The location where user-defined error labels are displayed. First parameter: An error label as a jquery object, and the second argument is a form element that is not validated as a jquery object.
JS Code
$ ("#myform"). Validate ({
Errorplacement:function (Error, Element) {
Error.appendto (Element.parent ("TD"). Next ("TD");
},
Debug:true
})
[Success] Type: String,callback
Description: If it is specified, a message is displayed when validation passes. If it is of type string, the style is added to the label, and if it is a callback function, the label is the only parameter.
JS Code
$ ("#myform"). Validate ({
Success: "Valid",
Success:function (label) {
Label.addclass ("valid"). Text ("ok!")
}
})
[Highlight] Type: Callback default: Add Errorclass to form element
Description: Highlights the form elements that are not validated.
JS Code
$ (". Selector"). Validate ({
highlight:function (element, Errorclass) {
$ (Element). fadeout (function () {
$ (Element). FadeIn ()
})
}
})
[24] unhighlight type: callback & nbsp; default: Removing errorclass
Description: Contrary to highlight action
JS Code
$ (". 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);
}
});
[25] ignoretitle type:boolean default: false
Note: Set up a reference to the title property that skips the error message to avoid conflicts caused by the Google toolbar.
JS Code
$ (". Selector"). Validate ({
Ignoretitle:true
})
Original address: Http://docs.jquery.com/Plugins/Validation/validate#toptions
Second, plug-in method (Plugin methods)
[1] Validate ([options]) returns: Validator
Note: See part I.
[2] Valid () return: Boolean
Description: Checks whether the form has passed validation.
JS Code
$ ("#myform"). Validate ();
$ ("A.check"). Click (function () {
Alert ("Valid:" + $ ("#myform"). Valid ());
return false;
});
[3] Rules () return: Options
Description: Returns the validation rules for a FORM element. There are several ways to define validation rules:
Define validation rules (recommended methods) in the class attribute of the form element.
By specifying the properties of the validation method (the recommended method).
Metadata validation rules can be defined through a metadata (metadata) plug-in.
You can specify the rules option for the Validate () method.
JS Code
Alert ($ ("#password"). Rules () ["required"]);
[4] Rules ("Add", rules) return: Options
Parameter ' Add ' type: String
Parameter rules type: Options the rules to add are consistent with the validation rules in the Validate method.
Description: Adds a rule to a matching form element, returns all validation rules for that element, and needs to execute $ ("form") first. Validate (). You can also add user-customized message objects in the rules.
JS Code
$ ("#myinput"). Rules ("add", {
Required:true,
Minlength:2,
Messages: {
Required: "Required input",
Minlength:jQuery.format ("Please, at least {0} characters are necessary")
}
});
[5] Rules ("Remove", [rules]) return: Options
Parameter ' remove ' type: String
Argument rules (Options) Type: The validation rules for options to be split with whitespace characters. Only the validation rules specified by the rules option or rules ("add") are manipulated.
Description: Removes the specified validation rule from the first matching form element and returns all validation rules for that element.
JS Code
$ ("#myinput"). Rules ("Remove");
$ ("#myinput"). Rules ("Remove", "Min Max");
[6] Removeattrs (attributes) return: Options
Parameter attributes type: A list of attributes separated by a white space character String
Description: Deletes the specified properties from the first matching form element and returns them.
JS Code
$ ("#skip"). Click (function () {
var rules = $ ("#myinput"). Removeattrs ("min Max");
$ ("#myform)". Submit ();
$ ("#myinput"). attr (rules);
});
Third, custom selector (custom selectors)
[1]: Blank returns:array<element>
Description: A form element that matches all null values. No value or both whitespace characters (whitespace) are considered null values.
It is judged by Jquery.trim (value). length = = 0来.
JS Code
$ ("Input:blank"). CSS ("Background-color", "#bbbbff");
[2]: Filled returns:array<element>
Description: Matches all form elements that are not empty. Any value can be considered entered, except for values that have whitespace.
It is judged by Jquery.trim (value). length > 0来.
JS Code
$ ("input:filled"). CSS ("Background-color", "#bbbbff");
[3]: Unchecked returns:array<element>
Description: Matches all of the selected form elements. The reverse action is: checked
JS Code
function countunchecked () {
var n = $ ("input:unchecked"). Length;
$ ("div"). Text (n + (n = 1?) "is": "are") + "unchecked!");
}
Countunchecked ();
$ (": CheckBox"). Click (countunchecked);
Iv. Practical Tools (Utilities)
JQuery.validator.format (template, [argument], [argumentn ...]) return: String
parameter template type:string The string to be formatted
parameter argument (Optional) type: string, array<string> Fills the first placeholder
parameter argumentn with a string or string array (the elements of the corresponding index) ... (Optional) type:string fills the second or subsequent placeholder.
Description: Fills {n} placeholders with parameters. One or more parameters, except template, can be used to populate the appropriate placeholders.
JS Code
$ (document). Ready (function () {
$ ("button"). Click (function () {
var str = "Hello {0}, this is {1}";
Alert ("'" + str + "");
str = JQuery.validator.format (str, "World", "Bob");
str = $.validator.format (str, ["Koala", "oo"]);
Alert ("'" + str + "");
});
});
V. Validator (Validator)
The Validator object (Validator object) returned by the Validate method has some common methods. You can use it to trigger a validator or change the contents of a form. Validator objects have more methods, but only the methods given in the document are designed for use.
(i) Validator method (Validator methods)
[1] form () return: Boolean
Note: Verify that the form is authenticated, return TRUE if it is validated, and return false instead. This method is triggered at the normal commit event (submit events), and it returns a result.
JS Code
$ ("#myform"). Validate (). form ();
[2] Element (Element) returns: Boolean
Parameter element type: Selector verifies a FORM element that needs to be validated in the form.
Description: Verifies that a single form element is authenticated, returns True if it is validated, and returns false. This method fires when the normal focus leaves the event (blur) or when the key bounces (KeyUp), and it returns a result.
JS Code
$ ("#myform"). Validate (). Element ("#myselect");
[3] Resetform () return: undefined
Description: Resets the form.
Restores the form element to its original value (requires form plug-in support), removes the invalid validation style, and hides the error message.
(... It seems that only under IE can remove the style)
JS Code
var validator = $ ("#myform"). Validate ();
Validator.resetform ();
[4] showerrors (errors) return: undefined
Parameter errors type: object<string, string> a key/value pair that consists of the Name property of one or more form elements and the validation message.
Description: Displays the specified validation message.
Displays the validation message in the specified errorplacement. The key is the Name property of the form element to be validated, and the value is the appropriate validation message.
JS Code
var validator = $ ("#myform"). Validate ();
Validator.showerrors ({"FirstName": "I know that your FirstName is Pete, pete!"});
[5] Numberofinvalids () return: Integer
Description: Returns the number of form elements that have not been validated.
This method relies on internal validator conditions. All form elements that are to be validated (the submit event or through $ ("form") are counted only when all the form element is validated. Valid ()). When only a single form element is validated, only the form element is counted. is useful when used in conjunction with the Invalidhandler option.
JS Code
var validator = $ ("#myform"). Validate ({
Invalidhandler:function () {
$ ("#summary"). Text (Validator.numberofinvalids () + "field (s) areinvalid");
}
});
(ii) Validator functions (Validator functions)
[1] setdefaults (defaults) return: undefined
Parameter defaults type: Options to set the default value.
Description: Modifies the default settings for the validation framework.
Accept all options in the Validate method.
JS Code
JQuery.validator.setDefaults ({
debug:true
});
[2] Addmethod (name, method, [message]) return: undefined
parameter name type:string The name of the method to add, for identification and reference, must be a valid JavaScript identifier.
parameter method type:callback the implementation part of the method, returns true if the form element passes validation.
Parameter Message (Optional) type: String to function the default validation messages for this method. Can be created using the JQuery.validator.format (value) method. If this parameter is not defined, the validation message that already exists locally is used, and the validation message must be defined for the specified form element.
Description: Adds a user-defined authentication method. It consists of a method name (which must be a valid JavaScript identifier), a JavaScript based function, and a default validation message.
JS Code
JQuery.validator.addMethod ("Math", function (value, element, params) {
return this.optional (Element) | | Value = = Params[0] + params[1];
}, Jquery.format ("Please enter the correct value for {0} + {1}"));
[3] Addclassrules (name, rules) return: undefined
Parameter name type: String The name of the style rule to add.
Parameter rules type: Options rule option.
Description: Adds a composite style validation method. It is useful to refactor multiple federated rules into a single style.
JS Code
JQuery.validator.addClassRules ("name", {
Required:true,
Minlength:2
});
[4] Addclassrules (rules) return: undefined
Parameter rules type: Options style class name-rule table.
Description: Adds a composite style validation method. is useful for refactoring common union rules.
JS Code
JQuery.validator.addClassRules ({
Name: {
Required:true,
Minlength:2
},
Zip: {
Required:true,
Digits:true,
Minlength:5,
Maxlength:5
}
});
Vi. Framework-built verification method (List of built-in Validation methods)
[1] Required () return: Boolean
Description: Make the form elements must be filled in (select).
If the form element is empty (text input) or is not selected (Radio/checkbox) or a null value (select) is selected.
Acts on text inputs, selects, checkboxes and radio buttons.
When the Select provides a null value option <option value= "" >Choose...</option> forces the user to select a value that is not empty.
JS Code
$ ("#myform"). Validate ({
rules: {
fruit: "Required"
}
});
[2] required (dependency-expression) return: Boolean
Parameters dependency-expression type:string An expression (String) in the form context. Whether a form element needs to be filled in depends on the expression to return one or more elements.
Description: Make form elements Mandatory (select), dependent on the return value of the parameter.
Expressions like #foo:checked, #foo: Filled, #foo: visible Such a selection filter will often be used.
JS Code
$ ("#myform"). Validate ({
rules: {
details: {
Required: "#other: Checked"
}
}, Debug:true
});
$ ("#other"). Click (function () {
$ ("#details"). valid ();
});
[3] required (dependency-callback) return: Boolean
Parameter The dependency-callback type:callback the callback function to validate the form element as its only parameter. This form element is required when the callback function returns TRUE.
Description: Make form elements Mandatory (select), dependent on the return value of the parameter.
Expressions like #foo:checked, #foo: Filled, #foo: visible Such a selection filter will often be used.
JS Code
$ ("#myform"). Validate ({
rules: {
Age: {
Required:true,
min:3
},
Parent: {
required:function (Element) {
Return $ ("#age"). Val () < 13;
}
}
}
});
$ ("#age"). blur (function () {
$ ("#parent"). valid ();
});
[4] Remote (options) return: Boolean
parameter options type: string, options Request server-side resource URL (string). Or options in the $.ajax () method.
Description: Request Server-side resource validation.
Server-side resources get Key/value pairs through $.ajax (XMLHttpRequest), and the response returns true the form passes validation.
JS Code
$ ("#myform"). Validate ({
rules: {
email: {
& nbsp Required:true,
email:true,
Remote: " check-email.php "
}
}
}";
[5] minlength (length) return: Boolean
parameter length type:integer At least the number of characters required.
Description: Make sure that the form element satisfies the given minimum number of characters.
There are too few characters entered in the text box, not enough check boxes (checkboxes) selected, and not enough options in a Select box (select). This method returns false in the above three cases.
JS Code
$ ("#myform"). Validate ({
rules: {
field: {
& nbsp Required:true,
minlength:3
}
}
};
[6] maxlength (length) return: Boolean
parameter length type:integer The maximum number of characters allowed to enter.
Description: Ensure that the text of a form element does not exceed the given maximum number of characters. The
has too many characters entered in the text box, too many check boxes (checkboxes), and a selection box (select) does not have too many options selected. This method returns false in the above three cases.
JS Code
$ ("#myform"). Validate ({
rules: {
field: {
& nbsp Required:true,
maxlength:4
}
}
};
[7] rangelength (range) return: Boolean
parameter range type:array<integer> the number of characters allowed to enter.
Description: Make sure that the number of text characters in the form element is within a given range.
The number of characters entered in the text box is not within a given range, the selected check box (checkbox) is not in the given range, and the option selected for a selection box (select) is not in the given range. This method returns false in the above three cases.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Rangelength: [2, 6]
}
}
});
[8] min (value) returns: Boolean
Parameter value type: The smallest integer required to enter.
Note: Make sure that the value of the form element is greater than or equal to the given minimum integer.
This method is only valid under Text input box.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Min:13
}
}
});
[9] Max (value) returns: Boolean
Parameter value type: The largest integer given by integer.
Note: Make sure that the value of the form element is less than the maximum integer given.
This method is only valid under Text input box.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Max:23
}
}
});
[A] range (range) returns: Boolean
The parameter range type:array<integer> the given integer range.
Note: Make sure that the value of the form element is within a given range.
This method is only valid under Text input box.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Range: [13, 23]
}
}
});
[One] Email () Return: Boolean
Note: Make sure that the value of the form element is a valid email address.
Returns True if the value is a valid email address. This method is only valid under Text input box.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Email:true
}
}
});
[A] URL () return: Boolean
Note: Make sure that the value of the form element is a valid URL address (http://www.mydomain.com).
Returns True if the value is a valid URL address. This method is only valid under Text input box.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Url:true
}
}
});
[A] Date () Dateiso () Datede () returns: Boolean
Description: Used to validate a valid date. Each of these three functions validates the date format (mm/dd/yyyy), (YYYY-MM-DD,YYYY/MM/DD), (MM.DD.YYYY).
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Date:true
}
}
});
[?] Number () Numberde () return: Boolean
Description: Used to verify decimals. The decimal point for number () is a dot (.), and the decimal point for Numberde () is an English comma (,).
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Number:true
Numberde:true
}
}
});
[A] digits () Back: Boolean
Note: Make sure that the value in the text box is a number.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Digits:true
}
}
});
[[] Digits () Back: Boolean
Note: Make sure that the value in the text box is a number.
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Digits:true
}
}
});
[] Accept ([extension]) return: Boolean
Parameter extension (Optional) Type: String allowed file suffix name, with "|" Or "," split. Default to "Png|jpe?g|gif"
Note: Make sure that the form element receives a file with the given file suffix name. If you do not specify a parameter, only the picture is allowed (png,jpeg,gif).
JS Code
$ ("#myform"). Validate ({
Rules: {
Field: {
Required:true,
Accept: "Xls|csv"
}
}
});
[A] Equalto (other) returns: Boolean
Parameter other type: Selector another form element to compare to the current value.
Note: Make sure that the values of the two form elements are the same.
JS Code
$ ("#myform"). Validate ({
Rules: {
Password: "Required",
Password_again: {
Equalto: "#password"
}
}
});
VII. Matters needing attention
[1] Complex Name property value
When you use the Rules option, if the form's Name property value contains an illegal JavaScript identifier, you must enclose the name value in quotation marks.
JS Code
$ ("#myform"). Validate ({
rules: {
//No quoting necessary
& nbsp Name: "Required",
//quoting necessary!
"User[email]": "Email",
//Dots need quoting, too!
"User.address.street": "Required"
}
});
[2] refactoring rules
Refactoring rules can reduce a lot of repetition whenever you have multiple fields in your form that contain the same validation rules and validation messages. Using Addmethod and Addclassrules will be very effective.
If the following rules have been refactored:
JS Code
Alias required to crequired with the new message
$.validator.addmethod ("crequired", $.validator.methods.required,
"Customer name required");
Alias MinLength, too
$.validator.addmethod ("Cminlength", $.validator.methods.minlength,
Leverage parameter replacement for minlength, {0} gets replaced with 2
$.format ("Customer name must have at least {0} characters"));
Combine them both, including the parameter for minlength
$.validator.addclassrules ("Customer", {crequired:true, cminlength:2});
Then use the time as follows:
HTML code
<input name= "customer1″class=" Customer "/>
<input name= "customer2″class=" Customer "/>
<input name= "customer3″class=" Customer "/>
[3] Authentication message
When an invalid form element is validated, the validation message appears in front of the user. Where did the news come from? There are three ways to get validation messages.
1. To validate the title property of a FORM element
2. Through the default validation message
3. Through the plug-in settings (Messages option)
The priorities for these three approaches are: 3 > 1 > 2
[4] Verify that the message conflicts with Google Toolbar
Sometimes the validation message conflicts with the AutoFill plug-in of the Goole toolbar. AutoFill displays a hint message by replacing the title property of the form element. At this point, if the validation message gets the value of the title attribute, then the result is not what we expect it to be. When a document is loaded, you can avoid conflicts by using the following methods.
JS Code
$ ("Input.remove_title"). attr ("title", "");
[5] form submission
By default, the form is blocked from submitting when the form validation fails, and when validation passes, the form is submitted. Of course, you can also customize the commit event by Submithandler.
Set the class property of the Submit button to cancel, and you can skip validation when the form is submitted.
JS Code
<input type= "Submit" name= "submit" value= "Submit"/>
<input type= "Submit" class= "Cancel" name= "Cancel" value= "Cancel"/>
The following code loops through the form:
Java code
$ ("#myform"). Validate ({
Submithandler:function (form) {
Some other code maybe disabling submit button
Then
$ (form). Submit ();
}
});
$ (form). Submit () triggers another round of validation, validates and then invokes Submithandler, then loops. You can use Form.submit () to trigger the native form submission event.
Java code
$ ("#myform"). Validate ({
Submithandler:function (form) {
Form.submit ();
}
});
VIII. Application Examples
[1] Validation page
HTML code
<%@ page language= "java" import= "java.util.*" pageencoding= "gb2312″%>
<html>
<head>
<title>jquery Verification Framework </title>
<link rel= "stylesheet" type= "Text/css" href= "Css/index.css" >
<script type= "Text/javascript" src=js/jquery-1.3.2.min.js></script>
<script type= "Text/javascript" src=js/jquery.validate.pack.js></script>
<script type= "Text/javascript" src=js/jquery.form.js></script>
<script type= "Text/javascript" src=js/valid.js></script>
<style type= "Text/css" >
label {width:10em; float:left;}
Label.haha {color:red; padding-left:18px; vertical-align:top;width:196px; Background:url ("Images/unchecked.gif") No-repeat;}
Input.haha {border:1px solid red;}
Label.valid {background:url ("images/checked.gif") no-repeat; color: #065FB9;}
Input.focus {border:2px solid green;}
UL li{Display:block;}
</style>
</head>
<body>
<div id= "Form_con" >
<form class= "Cmxform" id= "MyForm" method= "POST" action= "" >
<table cellspacing= "0″cellpadding=" 0″>
<tbody>
<tr>
<td> User name </td>
<td><input type= "text" name= "username" class= "required"/></td>
<td></td>
</tr>
<tr>
<td> Password </td>
<td><input id= "password" type= "password" name= "Firstpwd"/></td>
<td></td>
</tr>
<tr>
<td> Authentication Password </td>
<td><input type= "Password" name= "Secondpwd"/></td>
<td></td>
</tr>
<tr>
<td> Sex </td>
<td><input id= "Sex" type= "Radio" name= "Sex"/> Male <input type= "Radio" name= "Sex"/> Women </td>
<td></td>
</tr>
<tr>
<td> Age </td>
<td><input type= "text" name= "age"/></td>
<td></td>
</tr>
<tr>
<td> Email </td>
<td><input type= "text" name= "email"/></td>
<td></td>
</tr>
<tr>
<td> Personal Homepage </td>
<td><input type= "text" name= "Purl"/></td>
<td></td>
</tr>
<tr>
<td> Tel </td>
<td><input type= "text" name= "Telephone"/></td>
<td></td>
</tr>
<tr>
<td> Accessories </td>
<td><input type= "File" Name= "Afile"/></td>
<td></td>
</tr>
<TR><TD colspan= "3″><input type=" Submission "name=" submit "value=" submitting "/><button> Reset </button ></td></tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
[2] Verify JS
JS Code
$ (function () {
var validator = $ ("#myform"). Validate ({
Debug:true,//debug mode Cancel submit default submission function
Errorclass: "haha",//default is the wrong style class for: Error
Focusinvalid:false,
Onkeyup:false,
Submithandler:function (form) {//form submission handle, for a callback function with one parameter: form
Alert ("Submit form");
Form.submit (); Submitting a form
},
Rules: {//define validation rules, where the property name is the form's Name property
Username: {
Required:true,
Minlength:2,
Remote: "uservalid.jsp"//Legendary AJAX validation
},
Firstpwd: {
Required:true,
Minlength:6
Rangelength: [6,8]
},
Secondpwd: {
Required:true,
Equalto: "#password"
},
Sex: {
Required:true
},
Age: {
Required:true,
Range: [0,120]
},
Email: {
Required:true,
Email:true
},
Purl: {
Required:true,
Url:true
},
Afile: {
Required:true,
Accept: "Xls,doc,rar,zip"
}
},
Messages: {//custom validation message
Username: {
Required: "User name is required!" ”,
MinLength: $.format ("username must be at least {0} characters!") ”),
Remote: $.format ("{0} already occupied")
},
Firstpwd: {
Required: "The password is required!" ”,
Rangelength: $.format ("password to be between {0}-{1} characters!") ”)
},
Secondpwd: {
Required: "Password verification is required!" ”,
Equalto: "Password verification needs to be consistent with password"
},
Sex: {
Required: "Sex is required"
},
Age: {
Required: "Age is required",
Range: "Age must be between {0}-{1}"
},
Email: {
Required: "The mailbox is required!" ”,
Email: "Please enter the correct email address (e.g. myemail@163.com)"
},
Purl: {
Required: "Personal homepage is required",
URL: "Please enter the correct URL format, such as http://www.domainname.com"
},
Afile: {
Required: "Accessories are required!" ”,
Accept: "Only receive Xls,doc,rar,zip files"
}
},
Errorplacement:function (Error, Element) {//verify where the message is placed
Error.appendto (Element.parent ("TD"). Next ("TD");
},
Highlight:function (element, Errorclass) {//For validated form settings highlighting
$ (Element). addclass (Errorclass);
},
Success:function (label) {
Label.addclass ("valid"). Text ("ok!")
}
});
$ ("button"). Click (function () {
Validator.resetform ();
});
Alert ($ ("#password"). Rules () ["required"]);
Validator.showerrors ({"username": "User name is required"});
});
[3] Remote Authentication program
Java Code
<%@ page language= "java" import= "Java.io.PrintWriter" pageencoding= "gb2312″%><%
String username = request.getparameter ("username");
PrintWriter pw = Response.getwriter ();
try{
if (Username.tolowercase (). Equals (" Admin ") {
pw.println (" true ");
}else{
PW.PRINTLN ("false");
}
}catch (Exception ex) {
ex.getstacktrace ();
}finally{
pw.flush ();
Pw.close ();
}
%>