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

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>

分类:Web 时间:2010-06-21 人气:273
blog comments powered by Disqus


  • JavaScript 自动分号插入(JavaScript synat:auto semicolon insertion) 2015-03-24

    今天在看<Extjs中文手册>的时候,写了四五行样例代码,结果IE和Firefox一直报错不通过. 看代码: HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1

  • JavaScript call apply使用 JavaScript对象的方法绑定到DOM事件后this指向问题 2014-03-02

    JavaScript对象与DOM对象进行绑定会遇到一个问题:如果被绑定的对象的方法中包含this关键字,当事件被触发时this指向的却是DOM对象,而不是之前的JS对象. 先来看看现象: <html> <head> <title>apply_and_call</title> </head> <body onload="init()"> <div id="testDiv" style=&qu

  • javascript如何创建表格(javascript绘制表格的二种方法) 2014-10-09

    利用js来动态创建表格有两种格式,appendChild()和insertRow.insertCell().两种方式其实差不多,但第一种有可能在IE上有问题,所以推荐大家使用第二种方法,看下面的解决和使用方法 1.inserRow()和insertCell()函数 insertRow()函数可以带参数,形式如下: insertRow(index):index从0开始 这个函数将新行添加到index的那一行前,比如insertRow(0),是将新行添加到第一行之前.默认的insertRow()函数

  • javascript 单例模式演示代码 javascript面向对象编程 2014-11-17

    单例模式的好处就是:类只实例化一次,省资源,节省开销,提高速度,学习js面向对象编程的朋友可以参考下. js的单例写法 JS单例模式 你是?(单例) 你是?(普通) [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] loop.js是一个单例模式的js类: //一开始就用new 无名类的方式创建.这样就实现了单例的功能. var loop = new (function(){ // 外部公共函数 // 无限循环的操作 this.setloop = function(fn){Infinit

  • javascript读取xml实现javascript分页 2015-04-07

    这篇文章主要介绍了javascript读取xml数据对其实现javascript分页效果,大家参考使用吧 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"

  • Commonly used javascript regular expression based validation code text box 2010-03-31

    1, can not be empty <input type="text""if(this.value.replace(/^ +| +$/g,'')=='')alert(' Cannot be empty !')"> 2, can only enter numbers in English and <input"if(/[^0-9a-zA-Z]/g.test(value))alert(' There is wrong ')"&

  • nginx gzip duplicate MIME type "text / html" 2010-09-14

    Instruction [# Gzip gzip] [# Gzip_buffers gzip_buffers] [# Gzip_comp_level gzip_comp_level] [# Gzip_min_length gzip_min_length] [# Gzip_http_version gzip_http_version] [# Gzip_proxied gzip_proxied] [# Gzip_types gzip_types] After the upgrade to the l

  • The file automatically generated by code generator, just write the template, you can generate any code 2010-05-31

    # This file generated automatically through the code generator, just write the template, you can generate any code # With a check: http://code.google.com/p/rapid-framework/

  • E-mail address entered by the user to determine the legality of the code 2010-10-12

    E-mail address in the special characters are allowed, we can e-mail address in the application to add legitimacy to judge, to avoid the user enters the wrong character. Code: - (BOOL) validateEmail: (NSString *) candidate { NSString * emailRegex = @

  • 如何用正则取input type="text"中的value 2014-02-04

    1.如何通过正则取input type="text"中的value呢? 2.如何过滤掉input type="checkbox"的标签? 这样只能达到正则取input type="text"中的value可是不能过滤掉input type="checkbox"的标签! alert [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] alert [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 解决: aler

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 闽ICP备15018612号

processed in 0.282 (s). 10 q(s)