Validate.js表单验证插件

官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validationjavascript

jQuery plugin: Validation 使用说明  php

转载自:http://blog.sina.com.cn/s/blog_608475eb0100h3h1.htmlcss

导入js库
<script src="../js/jquery.js" type="text/JavaScript"></script>
<script src="../js/jquery.validate.js" type="text/javascript"></script>html

2、默认校验规则
(1)required:true                必输字段
(2)remote:"check.PHP"      使用ajax方法调用check.php验证输入值
(3)email:true                    必须输入正确格式的电子邮件
(4)url:true                        必须输入正确格式的网址
(5)date:true                      必须输入正确格式的日期 日期校验ie6出错,慎用
(6)dateISO:true                必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22 只验证格式,不验证有效性
(7)number:true                 必须输入合法的数字(负数,小数)
(8)digits:true                    必须输入整数
(9)creditcard:                   必须输入合法的信用卡号
(10)equalTo:"#field"          输入值必须和#field相同
(11)accept:                       输入拥有合法后缀名的字符串(上传文件的后缀)
(12)maxlength:5               输入长度最可能是5的字符串(汉字算一个字符)
(13)minlength:10              输入长度最小是10的字符串(汉字算一个字符)
(14)rangelength:[5,10]      输入长度必须介于 5 和 10 之间的字符串")(汉字算一个字符)
(15)range:[5,10]               输入值必须介于 5 和 10 之间
(16)max:5                        输入值不能大于5
(17)min:10                       输入值不能小于10java

3、默认的提示
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眉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}.")
},jquery

修改提示信息,可在js代码中加入git

jQuery.extend(jQuery.validator.messages, {
  required: "必选字段",
  remote: "请修正该字段",
  email: "请输入正确格式的电子邮件",
  url: "请输入合法的网址",
  date: "请输入合法的日期",
  dateISO: "请输入合法的日期 (ISO).",
  number: "请输入合法的数字",
  digits: "只能输入整数",
  creditcard: "请输入合法的信用卡号",
  equalTo: "请再次输入相同的值",
  accept: "请输入拥有合法后缀名的字符串",
  maxlength: jQuery.validator.format("请输入一个 长度最可能是 {0} 的字符串"),
  minlength: jQuery.validator.format("请输入一个 长度最少是 {0} 的字符串"),
  rangelength: jQuery.validator.format("请输入 一个长度介于 {0} 和 {1} 之间的字符串"),
  range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
  max: jQuery.validator.format("请输入一个最大为{0} 的值"),
  min: jQuery.validator.format("请输入一个最小为{0} 的值")
});ajax

将此文件放入messages_cn.js中,在页面中引入<script src="../js/messages_cn.js" type="text/javascript"></script>:express

 

4、使用方式
1.将校验规则写到控件中json

复制代码

<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 id="signupForm" method="get" action="">
    <p>
        <label for="firstname">Firstname</label>
        <input id="firstname" name="firstname" class="required" />
    </p>
 <p>
  <label for="email">E-Mail</label>
  <input id="email" name="email" class="required email" />
 </p>
 <p>
  <label for="password">Password</label>
  <input id="password" name="password" type="password" class="{required:true,minlength:5}" />
 </p>
 <p>
  <label for="confirm_password">确认密码</label>
  <input id="confirm_password" name="confirm_password" type="password" class="{required:true,minlength:5,equalTo:'#password'}" />
 </p>
    <p>
        <input class="submit" type="submit" value="Submit"/>
    </p>
</form>

复制代码

使用class="{}"的方式,必须引入包:jquery.metadata.js

可使用以下的方法,修改提示内容:
class="{required:true,minlength:5,messages:{required:'请输入内容'}}"

在使用equalTo关键字时,后面的内容必须加上引号,以下代码:
class="{required:true,minlength:5,equalTo:'#password'}"

 

2.将校验规则写到js代码中

复制代码

$().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: "请输入姓名",
   email: {
    required: "请输入Email地址",
    email: "请输入正确的email地址"
   },
   password: {
    required: "请输入密码",
    minlength: jQuery.format("密码不能小于{0}个字 符")
   },
   confirm_password: {
    required: "请输入确认密码",
    minlength: "确认密码不能小于5个字符",
    equalTo: "两次输入密码不一致不一致"
   }
  }
    });
});

复制代码

//messages处,若是某个控件没有message,将调用默认的信息

复制代码

<form id="signupForm" method="get" action="">
    <p>
        <label for="firstname">Firstname</label>
        <input id="firstname" name="firstname" />
    </p>
 <p>
  <label for="email">E-Mail</label>
  <input id="email" name="email" />
 </p>
 <p>
  <label for="password">Password</label>
  <input id="password" name="password" type="password" />
 </p>
 <p>
  <label for="confirm_password">确认密码</label>
  <input id="confirm_password" name="confirm_password" type="password" />
 </p>
    <p>
        <input class="submit" type="submit" value="Submit"/>
    </p>
</form>

复制代码

 

required:true 必须有值
required:"#aa:checked"表达式的值为真,则须要验证
required:function(){}返回为真,表时须要验证
后边两种经常使用于,表单中须要同时填或不填的元素

 

5、经常使用方法及注意问题
1.用其余方式替代默认的SUBMIT
$().ready(function() {
 $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();
        }    
    });
});

使用ajax方式

 $(".selector").validate({     
 submitHandler: function(form) 
   {      
      $(form).ajaxSubmit();     
   }  
 }) 

能够设置validate的默认值,写法以下:
$.validator.setDefaults({
 submitHandler: function(form) { alert("submitted!");form.submit(); }
});

若是想提交表单, 须要使用form.submit()而不要使用$(form).submit()

2.debug,只验证不提交表单
若是这个参数为true,那么表单不会提交,只进行检查,调试时十分方便

$().ready(function() {
 $("#signupForm").validate({
        debug:true
    });
});
若是一个页面中有多个表单都想设置成为debug,用
$.validator.setDefaults({
   debug: true
})

3.ignore:忽略某些元素不验证
ignore: ".ignore"
4.更改错误信息显示的位置
errorPlacement:Callback

 Default: 把错误信息放在验证的元素后面 
指明错误放置的位置,默认状况是:error.appendTo(element.parent());即把错误信息放在验证的元素后面 
errorPlacement: function(error, element) {  
    error.appendTo(element.parent());  
}

//示例:

复制代码

<tr>
    <td class="label"><label id="lfirstname" for="firstname">First Name</label></td>
    <td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>
    <td class="status"></td>
</tr>
<tr>
    <td style="padding-right: 5px;">
        <input id="dateformat_eu" name="dateformat" type="radio" value="0" />
        <label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>
    </td>
    <td style="padding-left: 5px;">
        <input id="dateformat_am" name="dateformat" type="radio" value="1"  />
        <label id="ldateformat_am" for="dateformat_am">02/14/07</label>
    </td>
    <td></td>
</tr>
<tr>
    <td class="label">&nbsp;</td>
    <td class="field" colspan="2">
        <div id="termswrap">
            <input id="terms" type="checkbox" name="terms" />
            <label id="lterms" 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() );
}

复制代码

代码的做用是:通常状况下把错误信息显示在<td class="status"></td>中,若是是radio显示在<td></td>中,若是是 checkbox显示在内容的后面

errorClass:String  Default: "error" 
指定错误提示的css类名,能够自定义错误提示的样式

errorElement:String  Default: "label" 
用什么标签标记错误,默认的是label你能够改为em

errorContainer:Selector 
显示或者隐藏验证信息,能够自动实现有错误信息出现时把容器属性变为显示,无错误时隐藏,用处不大
errorContainer: "#messageBox1, #messageBox2"

errorLabelContainer:Selector
把错误信息统一放在一个容器里面。

wrapper:String
用什么标签再把上边的errorELement包起来

通常这三个属性同时使用,实如今一个容器内显示全部错误提示的功能,而且没有信息时自动隐藏

errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"

5更改错误信息显示的样式
设置错误提示的样式,能够增长图标显示,在该系统中已经创建了一个validation.css专门用于维护校验文件的样式

 

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;
}

6每一个字段验证经过执行函数
success:String,Callback
要验证的元素经过验证后的动做,若是跟一个字符串,会当作一个css类,也可跟一个函数
success: function(label) {
    // set &nbsp; as text for IE
    label.html("&nbsp;").addClass("checked");
    //label.addClass("valid").text("Ok!")
}
添加"valid" 到验证元素, 在CSS中定义的样式<style>label.valid {}</style>
success: "valid"

 

7验证的触发方式修改
下面的虽然是boolean型的,但建议除非要改成false,不然别乱添加。

onsubmit:Boolean  Default: true 
提交时验证. 设置惟false就用其余方法去验证
onfocusout:Boolean  Default: true 
失去焦点是验证(不包括checkboxes/radio buttons)
onkeyup:Boolean  Default: true 
在keyup时验证.
onclick:Boolean  Default: true 
在checkboxes 和 radio 点击时验证
focusInvalid:Boolean  Default: true 
提交表单后,未经过验证的表单(第一个或提交以前得到焦点的未经过验证的表单)会得到焦点
focusCleanup:Boolean  Default: false 
若是是true那么当未经过验证的元素得到焦点时,移除错误提示。避免和 focusInvalid 一块儿用

 

// 重置表单
$().ready(function() {
 var validator = $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();
        }    
    });
    $("#reset").click(function() {
        validator.resetForm();
    });

});

8异步验证
remote:URL
使用ajax方式进行验证,默认会提交当前验证的值到远程地址,若是须要提交其余的值,可使用data选项

remote: "check-email.php"

remote: {
    url: "check-email.php",     //后台处理程序
    type: "post",               //数据发送方式
    dataType: "json",           //接受数据格式   
    data: {                     //要传递的数据
        username: function() {
            return $("#username").val();
        }
    }
}


远程地址只能输出 "true" 或 "false",不能有其它输出

 

9添加自定义校验
addMethod:name, method, message
自定义验证方法


// 中文字两个字节
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("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));


// 邮政编码验证   
jQuery.validator.addMethod("isZipCode", function(value, element) {   
    var tel = /^[0-9]{6}$/;
    return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");

 

1.要在additional-methods.js文件中添加或者在jquery.validate.js添加
建议通常写在additional-methods.js文件中

2.在messages_cn.js文件添加:isZipCode: "只能包括中文字、英文字母、数字和下划线",

调用前要添加对additional-methods.js文件的引用。

 

 

10radio和checkbox、select的验证
 

1.radio的required表示必须选中一个
<input  type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />
<input  type="radio" id="gender_female" value="f" name="gender"/>

 

2.checkbox的required表示必须选中
<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />

checkbox的minlength表示必须选中的最小个数,maxlength表示最大的选中个数,rangelength:[2,3]表 示选中个数区间


<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />

 

    3.select的required表示选中的value不能为空
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
    <option value=""></option>
    <option value="1">Buga</option>
    <option value="2">Baga</option>
    <option value="3">Oi</option>
</select>

 

select的minlength表示选中的最小个数(可多选的select),maxlength表示最大的选中个 数,rangelength:[2,3]表示选中个数区间
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
    <option value="b">Banana</option>
    <option value="a">Apple</option>
    <option value="p">Peach</option>
    <option value="t">Turtle</option>
</select>

 

 

jQuery.validate 中文API   

 

名称

 

返回类型

 

描述

 

validate(options)

 

返回:Validator

 

验证所选的FORM

 

valid()

 

返回:Boolean

 

检查是否验证经过

 

rules()

 

返回:Options

 

返回元素的验证规则

 

rules("add",rules)

 

返回:Options

 

增长验证规则

 

rules("remove",rules)

 

返回:Options

 

删除验证规则

 

removeAttrs(attributes)

 

返回:Options

 

删除特殊属性而且返回他们

 

Custom selectors

 

:blank

 

返回:Validator

 

没有值的筛选器

 

:filled

 

返回:Array <Element 
>

 

有值的筛选器

 

:unchecked

 

返回:Array <Element 
>

 

没选择的元素的筛选器

 

Utilities

 

jQuery.format

 

(template,argument 
,argumentN...)

 

返回:String

 

用参数代替模板中的 
{n}

 

 

Validator:

 

validate方法返回一个Validator对象,它有不少方法, 让你能使用引起校验程序或者改变form的内容. validator对象有不少方法,但下面只是列出经常使用的

 

form()

 

返回:Boolean

 

验证form返回成功仍是失败

 

element(element)

 

返回:Boolean

 

验证单个元素是成功仍是失败

 

resetForm()

 

返回:undefined

 

把前面验证的FORM恢复到验证前原来的状态

 

showErrors(errors)

 

返回:undefined

 

显示特定的错误信息

 

 

Validator functions:

 

setDefaults(defaults)

 

返回:undefined

 

改变默认的设置

 

addMethod(name,method,message)

 

返回:undefined

 

添加一个新的验证方法. 必须包括一个独一无二的名字,一个JAVASCRIPT的方法和一个默认的信息

 

addClassRules(name,rules)

 

返回:undefined

 

增长组合验证类型 在一个类里面用多种验证方法里比较有用

 

addClassRules(rules)

 

返回:undefined

 

增长组合验证类型 在一个类里面用多种验证方法里比较有用,这个是一会儿加多个

 

 

内置验证方式:

 

required()

 

返回:Boolean

 

必填验证元素

 

required(dependency-expression)

 

返回:Boolean

 

必填元素依赖于表达式的结果

 

required(dependency-callback)

 

返回:Boolean

 

必填元素依赖于回调函数的结果

 

remote(url)

 

返回:Boolean

 

请求远程校验。url一般是一个远程调用方法

 

minlength(length)

 

返回:Boolean

 

设置最小长度

 

maxlength(length)

 

返回:Boolean

 

设置最大长度

 

rangelength(range)

 

返回:Boolean

 

设置一个长度范围[min,max]

 

min(value)

 

返回:Boolean

 

设置最大值

 

max(value)

 

返回:Boolean

 

设置最小值

 

email()

 

返回:Boolean

 

验证电子邮箱格式

 

range(range)

 

返回:Boolean

 

设置值的范围

 

url()

 

返回:Boolean

 

验证URL格式

 

date()

 

返回:Boolean

 

验证日期格式(相似30/30/2008的格式,不验证日期准确性只验证格式)

 

dateISO()

 

返回:Boolean

 

验证ISO类型的日期格式

 

dateDE()

 

返回:Boolean

 

验证德式的日期格式(29.04.1994 or 
1.1.2006)

 

number()

 

返回:Boolean

 

验证十进制数字(包括小数的)

 

digits()

 

返回:Boolean

 

验证整数

 

creditcard()

 

返回:Boolean

 

验证信用卡号

 

accept(extension)

 

返回:Boolean

 

验证相同后缀名的字符串

 

equalTo(other)

 

返回:Boolean

 

验证两个输入框的内容是否相同

 

phoneUS()

 

返回:Boolean

 

验证美式的电话号码

 

 

validate ()的可选项:

 

debug:进行调试模式(表单不提交):

 

$(".selector").validate

 

({

 

   debug:true

 

})

 

把调试设置为默认:

 

$.validator.setDefaults({

 

   debug:true

 

})

 

submitHandler:

 

经过验证后运行的函数,里面要加上表单提交的函数,不然表单不会提交

 

$(".selector").validate({

 

   submitHandler:function(form) 
{

 

$(form).ajaxSubmit();

 

   }

 

})

 

ignore:

 

对某些元素不进行验证

 

$("#myform").validate({

 

   ignore:".ignore"

 

})

 

rules:

 

自定义规则,key:value的形式,key是要验证的元素,value能够是字符串或对象

 

$(".selector").validate({

 

   rules:{

 

     name:"required",

 

     email:{

 

       required:true,

 

       email:true

 

     }

 

   }

 

})

 

messages:

 

自定义的提示信息key:value的形式key是要验证的元素,值是字符串或函数

 

$(".selector").validate({

 

   rules:{

 

     name:"required",

 

     email:{

 

       required:true,

 

       email:true

 

     }

 

   },

 

   messages:{

 

     name:"Name不能为空",

 

     email:{

 

       
required:"E-mail不能为空",

 

       email:"E-mail地址不正确"

 

     }

 

   }

 

})

 

groups:

 

对一组元素的验证,用一个错误提示,用error Placement控制把出错信息放在哪里

 

$("#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

 

})

 

Onubmit Boolean 默认:true

 

是否提交时验证

 

$(".selector").validate({

 

   
onsubmit:false

 

})

 

onfocusout Boolean 默认:true  

 

是否在获取焦点时验证

 

$(".selector").validate({

 

   
onfocusout:false

 

})

 

onkeyup Boolean 默认:true  

 

是否在敲击键盘时验证

 

$(".selector").validate({

 

   onkeyup:false

 

})

 

onclick Boolean 默认:true

 

是否在鼠标点击时验证(通常验证checkbox,radiobox)

 

$(".selector").validate({

 

   onclick:false

 

})

 

focusInvalid Boolean 默认:true

 

提交表单后,未经过验证的表单(第一个或提交以前得到焦点的未经过验证的表单)会得到焦点

 

$(".selector").validate({

 

   focusInvalid:false

 

})

 

focusCleanup Boolean 默认:false

 

当未经过验证的元素得到焦点时,并移除错误提示(避免和 focusInvalid.一块儿使用)

 

$(".selector").validate({

 

   focusCleanup:true

 

})

 

errorClass String 默认:"error"

 

指定错误提示的css类名,能够自定义错误提示的样式

 

$(".selector").validate({

 

   
errorClass:"invalid"

 

})

 

errorElement String 默认:"label"

 

使用什么标签标记错误

 

$(".selector").validate

 

   errorElement:"em"

 

})

 

wrapper String

 

使用什么标签再把上边的errorELement包起来

 

$(".selector").validate({

 

   wrapper:"li"

 

})

 

errorLabelContainer Selector

 

把错误信息统一放在一个容器里面

 

$("#myform").validate({

 

   
errorLabelContainer:"#messageBox",

 

   wrapper:"li",

 

   submitHandler:function() { 
alert("Submitted!") }

 

})

 

 

 

showErrors:

 

跟一个函数,能够显示总共有多少个未经过验证的元素

 

$(".selector").validate({

 

   
showErrors:function(errorMap,errorList) {

 

        $("#summary").html("Your 
form contains " + this.numberOfInvalids() + " errors,see details 
below.");

 

        
this.defaultShowErrors();

 

   }

 

})

 

errorPlacement:

 

跟一个函数,能够自定义错误放到哪里

 

$("#myform").validate({

 

  
rrorPlacement:function(error,element) {  
error.appendTo(element.parent("td").next("td"));

 

   },

 

   debug:true

 

 

 

})

 

success:

 

要验证的元素经过验证后的动做,若是跟一个字符串,会当作一个css类,也可跟一个函数

 

$("#myform").validate({

 

        
success:"valid",

 

        submitHandler:function() 
{ alert("Submitted!") }

 

})

 

highlight:

 

能够给未经过验证的元素加效果,闪烁等

 

 

 

 

addMethod(name,method,message)方法:

 

参数name是添加的方法的名字

 

参数method是一个函数,接收三个参数(value,element,param) 
value是元素的值,element是元素自己 
param是参数,咱们能够用addMethod来添加除built-in Validation 
methods以外的验证方法 好比有一个字段,只能输一个字母,范围是a-f,写法以下:

 

 

 

$.validator.addMethod("af",function(value,element,params){

 

   
if(value.length>1){

 

    return false;

 

   }

 

   if(value>=params[0] 
&& value<=params[1]){

 

    return true;

 

   }else{

 

    return false;

 

   }

 

},"必须是一个字母,且a-f");

 

用的时候,好比有个表单字段的id="username",则在rules中写

 

username:{

 

   af:["a","f"]

 

}

 

 

 

addMethod的第一个参数,就是添加的验证方法的名子,这时是af

 

addMethod的第三个参数,就是自定义的错误提示,这里的提示为:"必须是一个字母,且a-f"

 

addMethod的第二个参数,是一个函数,这个比较重要,决定了用这个验证方法时的写法

 

若是只有一个参数,直接写,若是af:"a",那么a就是这个惟一的参数,若是多个参数,用在[]里,用逗号分开

 

 

meta String方式:

 

$("#myform").validate({

 

   meta:"validate",

 

   submitHandler:function() { 
alert("Submitted!") }

 

})

 

<script type="text/javascript" 
src="js/jquery.metadata.js"></script>

 

<script type="text/javascript" 
src="js/jquery.validate.js"></script>

 

<form id="myform">

 

  <input type="text" 
name="email" class="{validate:{ required:true,email:true }}" />

 

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

 

</form>

列子:

 

[html] view plain copy

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" >  
  3. <head runat="server">  
  4. <title>JQuery表单验证插件jQuery.validate.js</title>  
  5. <style type="text/css">  
  6. /******/  
  7. form.cmxform label.error, label.error {  
  8. color: red;  
  9. font-style: italic;  
  10. }  
  11. </style>  
  12. </head>  
  13. <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>  
  14. <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>  
  15. <body>  
  16. <form class="cmxform" id="commentForm" method="get" action="">  
  17. <fieldset>  
  18. <legend>注册帐号</legend>  
  19. <p>  
  20. <label for="cusername">用户名</label>  
  21. <input id="username" name="username" />  
  22. <p>  
  23. <label for="cemail">邮箱</label>  
  24. <input id="email" name="email" />  
  25. </p>  
  26. <p>  
  27. <label for="cpassword">密码</label>  
  28. <input type="password" id="password" name="password" value="" />  
  29. </p>  
  30. <p>  
  31. <label for="cconfirm_password">确认密码</label>  
  32. <input type="password" id="confirm_password" name="confirm_password" value="" />  
  33. </p>  
  34. <p>  
  35. <input class="submit" type="submit" value="提交"/>  
  36. </p>  
  37. </fieldset>  
  38. </form>  
  39. </body>  
  40. </html>  
  41. <script type="text/javascript" >  
  42.   
  43. $.validator.setDefaults({  
  44.         submitHandler: function() {  
  45.                 alert("已经提交!");  
  46.         }  
  47. });  
  48.   
  49. $().ready(function() {  
  50.       
  51.         $("#commentForm").validate({  
  52.                 rules: {  
  53.                     username: {  
  54.                             required:true,  
  55.                             minlength:2  
  56.                     },  
  57.                     email: {  
  58.                             required: true,  
  59.                             email: true  
  60.                     },  
  61.                     password: {  
  62.                         required: true,  
  63.                         minlength: 6  
  64.                     },  
  65.                     confirm_password: {  
  66.                         required: true,  
  67.                         minlength: 6,  
  68.                         equalTo: "#password"  
  69.                     }  
  70.                 },  
  71.                 messages: {  
  72.                     username: {  
  73.                             required:"用户名必填",  
  74.                             minlength:"至少2个字符"  
  75.                     },  
  76.                     email:"请输入一个邮件地址",  
  77.                     password: {  
  78.                         required: "请输入密码",  
  79.                         minlength: "密码不能少于6个字符"  
  80.                     },  
  81.                     confirm_password: {  
  82.                         required: "请输入确认密码",  
  83.                         minlength: "确认密码不能少于6个字符",  
  84.                         equalTo: "密码输入不一致"  
  85.                     }  
  86.                 }  
  87.         });  
  88.   
  89. });  
  90. </script>  
相关文章
相关标签/搜索