jQuery.validate use of essential

jQuery.validate is a very good form validation tools, simple approachable, and experience to achieve good results, although long used in the project, but seeing this article well written is good, reproduced under to share with you.

One must use the official website of the former: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
API: http://jquery.bassistance.de/api-browser/plugins.html
Current Version: 1.5.5
Need JQuery version: 1.2.6 +, Compatibility 1.3.2
<script src="../js/jquery.js" type="text/javascript"> </ script>
<script src="../js/jquery.validate.js" type="text/javascript"> </ script>

Second, the default validation rules
(1) required: true losing field
(2) remote: "check.php" using ajax method call check.php validate input values
(3) email: true must enter the correct e-mail format
(4) url: true must enter the correct URL format
(5) date: true must enter the correct date format
(6) dateISO: true must enter the correct date format (ISO), for example :2009-06-23, 1998/01/22 verification only format, do not verify the validity of
(7) number: true must enter a valid number (negative numbers, decimals)
(8) digits: true must enter an integer
(9) creditcard: must enter a valid credit card number
(10) equalTo: "# field" and the # field enter the value must be the same
(11) accept: Enter a valid extension of the string (upload the file extension)
(12) maxlength: 5 Enter the length of at most 5 string (character count as one character)
(13) minlength: 10 Enter the minimum length is 10 character string (character count as one character)
(14) rangelength: [5,10] must be between the input length of the string between 5 and 10 ") (character count as one character)
(15) range: [5,10] between the input value must be between 5 and 10
(16) max: 5 input value is not greater than 5
(17) min: 10 input value is not less than 10

Third, the default prompt
messages: {
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).",
dateDE: "Bitte geben Sie ein g eyebrow ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
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}.")
}
If you need to modify, add in the js code:
jQuery.extend (jQuery.validator.messages, {
required: "Required field",
remote: "Please correct the field,"
email: "Please enter a valid e-mail format"
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: "can only enter integer"
creditcard: "Please enter a valid credit card number,"
equalTo: "Please re-enter the same value"
accept: "Please enter a valid string extension"
maxlength: jQuery.validator.format ("Please enter a maximum length of the string is {0}")
minlength: jQuery.validator.format ("Please enter a minimum length of the string is {0}")
rangelength: jQuery.validator.format ("Please enter a length of between {0} and {1} string")
range: jQuery.validator.format ("Please enter a number between {0} and {1} value"),
max: jQuery.validator.format ("Please enter a maximum value of {0}")
min: jQuery.validator.format ("Please enter a minimum value of {0}")
});
Recommended practices, this file into messages_cn.js, in the introduction page
<script src="../js/messages_cn.js" type="text/javascript"> </ script>

Fourth, use
1. Will check write control rules
<script src="../js/jquery.js" type="text/javascript"> </ script>
<script src="../js/jquery.validate.js" type="text/javascript"> </ script>
<script src="./js/jquery.metadata.js" type="text/javascript"> </ script>
$ (). Ready (function () {
$ ("# SignupForm"). Validate ();
});

<form method="get" action="">
<p>
<label for="firstname"> Firstname </ label>
<input name="firstname" />
</ P>
<p>
<label for="email"> E-Mail </ label>
<input name="email" />
</ P>
<p>
<label for="password"> Password </ label>
<input name="password" type="password" />
</ P>
<p>
<label for="confirm_password"> Confirm Password </ label>
<input name="confirm_password" type="password" />
</ P>
<p>
<input type="submit" value="Submit"/>
</ P>
</ Form>
Use class ="{}" way, they must bring bag: jquery.metadata.js
You can use the following method, modify the prompts:
class = "{required: true, minlength: 5, messages: {required: 'Please enter content'}}"
EqualTo keywords using the back of the content must be in quotes, the following code:
class = "{required: true, minlength: 5, equalTo: '# password'}"
Another way of using keywords: meta (meta-data to use other plug-ins you want to wrap your validation rules in their own projects can use this special option)
Tell the validation plugin to look inside a validate-property in metadata for validation rules.
For example:
meta: "validate"
<input name="password" type="password" />

Another way:
$. Metadata.setType ("attr", "validate");
This can validate = "{required: true}" way, or class = "required", but the class = "{required: true, minlength: 5}" will not work

2. To write the code validation rules

$ (). Ready (function () {
$ ("# SignupForm"). Validate ({
rules: {
firstname: "required",
email: {
required: true,
email: true
}
password: {
required: true,
minlength: 5
}
confirm_password: {
required: true,
minlength: 5,
equalTo: "# password"
}
}
messages: {
firstname: "Please enter your name"
email: {
required: "Please enter the Email address",
email: "Please enter a valid email address"
}
password: {
required: "Please enter your password"
minlength: jQuery.format ("password can not be less than {0} characters")
}
confirm_password: {
required: "Please enter the confirmation code"
minlength: "Confirm password can not be less than 5 characters"
equalTo: "Enter the password twice inconsistent inconsistent"
}
}
});
});
/ / Messages at, if not a control message, will call the default message

<form method="get" action="">
<p>
<label for="firstname"> Firstname </ label>
<input name="firstname" />
</ P>
<p>
<label for="email"> E-Mail </ label>
<input name="email" />
</ P>
<p>
<label for="password"> Password </ label>
<input name="password" type="password" />
</ P>
<p>
<label for="confirm_password"> Confirm Password </ label>
<input name="confirm_password" type="password" />
</ P>
<p>
<input type="submit" value="Submit"/>
</ P>
</ Form>
required: true must have a value
required: "# aa: checked" expression is true, then the need to verify
required: function () {} return true, the table behind the need to verify that the two commonly used, the form needs to fill or not fill both elements

Five commonly used methods and attention problems
1. By other means instead of the default SUBMIT
$ (). Ready (function () {
$ ("# SignupForm"). Validate ({
submitHandler: function (form) {
alert ("submitted");
form.submit ();
}
});
});
Validate the default values can be set, written as follows:
$. Validator.setDefaults ({
submitHandler: function (form) {alert ("submitted!"); form.submit ();}
});
If you want to submit the form, you need form.submit () instead of $ (form). Submit ()

2.debug, if this parameter is true, then the form will not submit, just to check, very convenient for debugging
$ (). Ready (function () {
$ ("# SignupForm"). Validate ({
debug: true
});
});
If a page has multiple forms, with
$. Validator.setDefaults ({
debug: true
})

3.ignore: ignore some elements do not validate
ignore: ". ignore"

4.errorPlacement: Callback Default: the error message on the authentication element placed behind the specified error, default is: error.appendTo (element.parent ()); that the wrong information on the verification of the elements behind
errorPlacement: function (error, element) {
error.appendTo (element.parent ());
}
/ / Example:
<tr>
<td> <label for="firstname"> First Name </ label> </ td>
<td> <input name="firstname" type="text" value="" maxlength="100" /> </ td>
<td> </ td>
</ Tr>
<tr>
<td>
<input name="dateformat" type="radio" value="0" />
<label for="dateformat_eu"> 14/02/07 </ label>
</ Td>
<td>
<input name="dateformat" type="radio" value="1" />
<label for="dateformat_am"> 02/14/07 </ label>
</ Td>
<td> </ td>
</ Tr>
<tr>
<td> </ td>
<td colspan="2">
<div>
<input type="checkbox" name="terms" />
<label for="terms"> I have read and accept the Terms of Use. </ label>
</ Div>
</ Td>
</ Tr>
errorPlacement: function (error, element) {
if (element.is (": radio"))
error.appendTo (element.parent (). next (). next ());
else if (element.is (": checkbox"))
error.appendTo (element.next ());
else
error.appendTo (element.parent (). next ());
}
The role of the code is: Under normal circumstances the error message displayed in the <td> </ td>, if a radio show in <td> </ td>, if the content is displayed on the back of checkbox
errorClass: String Default: "error"
Specify the css error class name, you can customize the style error
errorElement: String Default: "label"
What is wrong with the tag, the default is the label you can change em
errorContainer: Selector
Show or hide authentication information, you can automatically have an error message appears when the container property into a show that no errors hidden usefulness
errorContainer: "# messageBox1, # messageBox2"
errorLabelContainer: Selector
The wrong information to be consolidated in a container inside.
wrapper: String
What label on top of the errorELement then wrapped up the three properties generally be used simultaneously to achieve in a container display all error functions, and are hidden when there is no information
errorContainer: "div.error",
errorLabelContainer: $ ("# signupForm div.error"),
wrapper: "li"

Set the error style, can increase the icon
input.error {border: 1px solid red;}
label.error {
background: url (". / demo / images / unchecked.gif") no-repeat 0px 0px;
padding-left: 16px;
padding-bottom: 2px;
font-weight: bold;
color: # EA5200;
}
label.checked {
background: url (". / demo / images / checked.gif") no-repeat 0px 0px;
}
success: String, Callback
To verify that the elements of the action is validated, if followed by a string, will be treated as a css class, but also with a function
success: function (label) {
/ / Set as text for IE
label.html (""). addClass ("checked");
/ / Label.addClass ("valid"). Text ("Ok!")
}
Add a "valid" to verify the elements defined in the CSS style <style> label.valid {} </ style>
success: "valid"

nsubmit: Boolean Default: true
Submission verification. CD set to false to verify with other methods
onfocusout: Boolean Default: true
Lost focus is to verify (not including checkboxes / radio buttons)
onkeyup: Boolean Default: true
When the keyup validation.
onclick: Boolean Default: true
Click the checkboxes and radio when the validation
focusInvalid: Boolean Default: true
After the form is submitted, not verified form (the first or get the focus before submitting the form is not validated) will be the focus
focusCleanup: Boolean Default: false
If it is true then when the element is not authenticated access to focus, to remove errors. Used together to prevent and focusInvalid

/ / Reset the form
$ (). Ready (function () {
var validator = $ ("# signupForm"). validate ({
submitHandler: function (form) {
alert ("submitted");
form.submit ();
}
});
$ ("# Reset"). Click (function () {
validator.resetForm ();
});
});

remote: URL
Way to use ajax validation, default values will be submitted to the current remote address verification, if required to submit any other value, you can use the data option
remote: "check-email.php"
remote: {
url: "check-email.php", / / background processing
type: "post", / / data transmission mode
dataType: "json", / / accept the data format
data: {/ / data to pass
username: function () {
return $ ("# username"). val ();
}
}
}

Remote address can only output "true" or "false", can not have other output

addMethod: name, method, message
Custom validation method

/ / Two bytes in the text
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 ("Please be sure to enter the value {0} - {1} bytes between (a Chinese character count 2 bytes )"));

/ / Postal Code authentication
jQuery.validator.addMethod ("isZipCode", function (value, element) {
var tel = / ^ [0-9] {6} $ /;
return this.optional (element) | | (tel.test (value));
}, "Please enter your zip code correctly");

radio and checkbox, select the authentication
The required radio said one must be selected
<input type="radio" value="m" name="gender" />
<input type="radio" value="f" name="gender"/>
The required checkbox that must be selected
<input type="checkbox" name="agree" />
must select the checkbox of the minlength that the minimum number, maxlength is the maximum number is selected, rangelength: [2,3] that the number of intervals selected
<input type="checkbox" value="email" name="spam[]" />
<input type="checkbox" value="phone" name="spam[]" />
<input type="checkbox" value="mail" name="spam[]" />

select the required selected value that can not be empty
<select name="jungle" title="Please select something!">
<option value=""> </ option>
<option value="1"> Buga </ option>
<option value="2"> Baga </ option>
<option value="3"> Oi </ option>
</ Select>
select the minlength that the minimum number of selected (multiple selection of the select), maxlength is the maximum number is selected, rangelength: [2,3] that the number of intervals selected
<select name="fruit" title="Please select at least two fruits" multiple="multiple">
<option value="b"> Banana </ option>
<option value="a"> Apple </ option>
<option value="p"> Peach </ option>
<option value="t"> Turtle </ option>
</ Select>
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of jQuery.validate use of essential

  • javascript regular expressions Basic Usage

    <script type="text/javascript"> window.onload = function(){ //RegExpInitialization ,gRefers to the global ,iIs case-insensitive var reg = new RegExp("cat","gi"); var exp = /cat/gi; //RegExpThe test ()Method ,The return value is true or false alert(r

  • Javascript Object Model

    Javascript Object Model

  • How to do a good job in the demand for change management - needs to change flow specification

    Project Leader: assessment needs to change some of the workload to determine whether it needs to change the contents of the progress on the development of an impact, if the demand to change the progress of an impact on the development, the project le ...

  • Use Ext JS to read the JsonReader complex object json

    Today was how to resolve the following complex json object to the difficult living over a long time .. did not find documentation how to read JsonReader Ways json object (possibly also because of their limited level of E the text did not correctly underst

  • JavaScript inheritance

    About JavaScript inherited a small example ... <! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.01 / / EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" conte ...

  • js page Jump implementation of a number of ways

    The first is: <script language="javascript" type="text/javascript"> window.location.href = "login.jsp? backurl =" + window.location.href; </ script> The second: <script language="javascript"> alert

  • Dynamic loading JS script four kinds of methods

    To achieve dynamic loading JS script has four kinds of methods: 1, direct document.write <script language="javascript"> document.write ( "<script src='test.js'> <\ / script>"); </ script> 2, dynamic scri

  • Hibernate Mapping Types

    Hibernate mapping types divided into two categories: built-in mapping types and mapping types of customers. Built-in mapping types is responsible for some common Java types are mapped to the corresponding SQL type; In addition, Hibernate also allows users

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries