jquery.validate.js Introduction to the basic usage (transfer)

sponsored links
jquery.validate.js is a verification under jquery plugin, features more powerful, but one does not already have heard of hands used, and now is able to look up.

Here is reproduced an article written by the older generation, in my own understanding of the changes a little, just for the record.

First, a large company posted a domestic code:

JavaScript code
  1. <script type="text/javascript">
  2. function lang (key) (
  3. mylang = (
  4. 'Ls_input_myb': 'Please enter your account'
  5. 'Ls_myb_email': 'roaming currency account for the email address'
  6. 'Ls_login_password': 'Please enter your password',
  7. 'Ls_password_length': 'password length is (0) - (1) bit between'
  8. 'Ls_input_captcha': 'Please enter the verification code',
  9. 'Ls_captcha_length': 'Code length is (0) bit',
  10. 'Ls_account_email': 'account name email address'
  11. '':''
  12. );
  13. return mylang [key];
  14. )
  15. </ Script>
  16. <script type="text/javascript">
  17. $ (Document). Ready (function () (
  18. $ ("# LoginForm"). Validate ((
  19. rules: (
  20. uEmail: (
  21. required: true,
  22. email: true
  23. )
  24. uPassword: (
  25. required: true,
  26. rangelength: [6, 30]
  27. )
  28. )
  29. messages: (
  30. uEmail: (
  31. required: lang ('ls_input_myb'),
  32. email: lang ('ls_myb_email')
  33. )
  34. uPassword: (
  35. required: lang ('ls_login_password'),
  36. rangelength: $. format (lang ('ls_password_length'))
  37. )
  38. )
  39. errorPlacement: function (error, element) (
  40. var placement = $ (element.parent ("td"). parent ("tr"). next ("tr"). find ("td"). get (1));
  41. placement.text ('');
  42. error.appendTo (placement);
  43. )
  44. onkeyup: false
  45. ));
  46. var accountTipsText = lang ('ls_account_email');
  47. $ ("# UEmail"). Focus (function () (
  48. if (!$($( this). parent (). parent (). next (). find ('td'). get (1)). text ()) (
  49. $ ($ (This). Parent (). Parent (). Next (). Find ('td'). Get (1)). Html ('<span>' + accountTipsText + '</ span>');
  50. )
  51. $ (This). Css ('color', '# 000');
  52. )). Focus ();
  53. ));
  54. </ Script>

I was starting from this example, the fact this case is almost the essence contains jquery.validate.js, if you a complete understanding of this code is basically regarded as a beginning.

Think before doing Futures website online simulation time to write their own code to determine the real infant death ... ... ... ...

The following is the complete article describes.

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, decimal)
(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: Input string has a valid suffix name (upload the file suffix)
(12) maxlength: 5 input length at most 5 string (character count as one character)
(13) minlength: 10 Enter the minimum length is 10 string (character count as one character)
(14) rangelength: [5,10] input length must be between 5 and 10 between the string ") (character count as one character)
(15) range: [5,10] input values must be between 5 and 10 between
(16) max: 5 input values can not be greater than 5
(17) min: 10 input values can not be less than 10
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).")
Such as the need to change, can be added 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 enter the same value again,"
accept: "Please enter the name of the string has a valid suffix"
maxlength: jQuery.validator.format ("Please enter a maximum 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 range of (0) and (1) string between")
range: jQuery.validator.format ("Please enter a range of (0) and (1) value between")
max: jQuery.validator.format ("Please enter a maximum value of (0)")
min: jQuery.validator.format ("Please enter a minimum value for the (0)")
Recommended practices, this file into messages_cn.js, in the introduction page
<script src="../js/messages_cn.js" type="text/javascript"> </ script>

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="">
<label for="firstname"> Firstname </ label>
<input name="firstname" />

<label for="email"> E-Mail </ label>
<input name="email" />

<label for="password"> Password </ label>
<input name="password" type="password" />

<label for="confirm_password"> Confirm Password </ label>
<input name="confirm_password" type="password" />

<input type="submit" value="Submit"/>
</ Form>

Use class ="{}" way to introduce package: jquery.metadata.js
You can use the following method, modify the content tips:
class = "(required: true, minlength: 5, messages: (required: 'Please enter content'))"
Using equalTo keywords, behind the content must be enclosed in quotation marks, 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 the 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: "Two password inconsistencies inconsistency"
/ / Messages office, if not a control message, will call the default message

<form method="get" action="">
<label for="firstname"> Firstname </ label>
<input name="firstname" />

<label for="email"> E-Mail </ label>
<input name="email" />

<label for="password"> Password </ label>
<input name="password" type="password" />

<label for="confirm_password"> Confirm Password </ label>
<input name="confirm_password" type="password" />

<input type="submit" value="Submit"/>
</ Form>

required: true must have a value
required: "# aa: checked" expression is true, you need to verify
required: function () () return true, the table need to verify the back of two types, the form need to fill or not fill the same time elements

Common 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, need to use form.submit () instead of using $ (form). Submit ()

2.debug, if this parameter is true, then the form will not submit, just checking, debugging is very convenient when
$ (). 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 validation of the elements specified in the error back to the position by default, is: error.appendTo (element.parent ()); that the error message on the validation of the elements behind
errorPlacement: function (error, element) (
error.appendTo (element.parent ());
/ / Example:
<td> <label for="firstname"> First Name </ label> </ td>
<td> <input name="firstname" type="text" value="" maxlength="100" /> </ td>
<td> </ td>
</ Tr>
<input name="dateformat" type="radio" value="0" />
<label for="dateformat_eu"> 14/02/07 </ label>
</ Td>
<input name="dateformat" type="radio" value="1" />
<label for="dateformat_am"> 02/14/07 </ label>
</ Td>
<td> </ td>
</ Tr>
<td> </ td>
<td colspan="2">
<input type="checkbox" name="terms" />
<label for="terms"> I have read and accept the Terms of Use. </ label>
</ 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 ());
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"
Specified error of the css class name, you can customize the style of errors
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, when no error concealment, use less
errorContainer: "# messageBox1, # messageBox2"
errorLabelContainer: Selector
The error message is unified in a container inside.
wrapper: String
What label on top of errorELement then wrap the three properties generally be used to achieve in a container show all errors, it also automatically hide when 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 through the validation, if with a string, will be treated as a css class can also be a function with
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
Verify the time of submission. Set the only false to use other methods to verify
onfocusout: Boolean Default: true
Loss of 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 (submitted prior to the first or the focus of the failed verification form) will be the focus
focusCleanup: Boolean Default: false
If this is true then when the element is not validated when the focus to remove errors. Used together to prevent and focusInvalid

/ / Reset 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, the default will be submitted to the current value to the remote address verification, if submitted to other values, you can use the data options
remote: "check-email.php"
remote: (
url: "check-email.php", / / background processing
type: "post", / / data send mode
dataType: "json", / / accept the data format
data: (/ / data to be passed
username: function () (
return $ ("# username"). val ();

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

addMethod: name, method, message
Custom authentication methods

/ / Two byte characters
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 2-byte characters count )"));

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

radio and checkbox, select the authentication
radio's required that 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 minlength that the minimum number, maxlength that selected the largest number, 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 select the minimum number (can be selected in the select), maxlength that selected the largest number, 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.js Introduction to the basic usage (transfer)

  • 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

  • RoR explained

    ROR is Ruby on Rails. Ruby is a well-known has been very good dynamic language It's dynamic language. Simple and easy. Dynamic languages are interpreted, but the performance may make a discount, but not absolute, because the application is complex, th

  • spring + hibernate + oracle9i to read and write CLOB

    Database-driven update classes12-9i.jar Hibernate modify the configuration of the following code <bean/> <bean Lazy-init="true"> <property name="nativeJdbcExtractor"> <ref local="nativejdbcExtractor"/>

  • Process migration from tomcat to websphere changes

    Process migration from tomcat to websphere changes Because customers use the web application server software used by different what tomcat5, tomcat6, websphere5.1, websphere6.1, weblogic8, and so on, and the software used inconsistent standards, ibm's

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

blog comments powered by Disqus
Recent Entries
Tag Cloud
Random Entries