validate() 表单验证插件的使用

来源:互联网 发布:淘宝玉兰油沐浴露 编辑:程序博客网 时间:2024/05/16 03:03

        validate() 是基于 jQuery 的一款表单验证插件,可是对它的具体使用却一直都一知半解,这两天正好遇到表单验证,就重新学习了一下这个插件,有些东西也是参考网友的,希望大家可以一起进步!

        首先,既然是基于 jQuery  的,那么第一步当然是引入 jQuery 库了:

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

        紧接着,既然 validate()  是一个插件,那么我们也需要引入它的源文件

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

        那么,这个插件本身到底是怎样进行验证的呢?这就需要我们了解一下它的默认验证规则

   

        需要注意的是 equalTo: 后面的值必须要加上引号和#,即必须是“#”格式的。

        规则这么多,我们要根据自己的表单情况合理选择。

         知道了 validate() 的默认验证规则(rules)后,下一步考虑如果验证不通过,那么 validate() 会以什么方式提示我们呢?一起来看看 validate() 的默认提示样式(messages):

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}.")},

         全是英文,看着是不是有些吃力?没办法,谁让这是人家外国人开发的呢,就是这么任性!但是这也不是什么难题,我们依然可以让它乖乖的用中文提示,只需要在你的 js 代码中加入以下代码即可:
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} 的值")});
        当然,你也可以更改其中的信息,比如将 required:"必选字段"  改为 required:"此字段不能为空!" ,也是可以的,你可以按照自己的心意来改变这些提示信息。可是,每次都在 js 代码中插入这些验证规则,是不是有些麻烦呢?反正我觉得是。。所以我更倾向于的做法是:将上面这段代码单独放入一个 js 中,命名为 validate_cn.js ,然后在引入 validate() 库时,顺便引入 validate_cn.js ,也向大家推荐这种做法。

        了解了 validate() 的验证规则和提示样式后,我们到底该怎样使用这种插件呢?我一般都是采取将校验规则写入 js 代码中(下文具体介绍)的方式,鉴于个人喜好不同,这里还是依次介绍:

        方式一:将校验规则写到控件中

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

       

        你注意到了吗?在代码开头我们除了引入 jQuery 库和 validate() 库之外,还引入了一个 metadata.js 的文件,这是因为我们将校验规则写到控件中时使用了 class="{}" 的方式,而使用这种方式,必须引入包:jquery.metadata.js

        可以使用如下的方法,修改提示内容:


class="{required:true,minlength:5,messages:{required:'请输入内容'}}"

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

           方式二:将验证规则写到 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: "两次输入密码不一致不一致" } } }); });
<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>

        $("#signupForm")  中 signupForm 是需要进行验证的表单的 id ,messages 处,如果某个控件没有 message,将调用默认的提示信息。

          required:true 必须有值,即不能为空。
        required:"#aa:checked" 表达式的值为真,则需要验证。
        required:function(){} 返回为真,表示需要验证。

        后边两种常用于,表单中需要同时填或不填的元素。


        接下来,还需要了解 validate()  的常用方法及注意问题:

        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.更改错误信息的提示位置:       

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

errorPlacement: function(error, element) {      error.appendTo(element.parent());  }


            demo:

<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"> </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 则显示在内容的后面。

       

        一般这三个属性同时使用,实现在一个容器内显示所有错误提示的功能,并且没有信息时自动隐藏:

errorContainer: "div.error",errorLabelContainer: $("#signupForm div.error"),wrapper: "li"
       5.更改错误信息的显示样式:

        validate() 默认为错误信息加上一个名字为 error 的类,我们可以通过这个来设置错误信息的显示样式:

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.每个字段验证通过执行函数:

        要验证的元素通过验证后的动作,如果跟一个字符串,会当作一个 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,否则别乱添加:

       

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

      

            8.异步验证:

        使用 ajax 方式进行验证,默认会提交当前验证的值到远程地址,如果需要提交其他的值,可以使用 data 选项:

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

       

           注意:远程地址只能输出 "true" 或 "false",不能有其他输出。

       9.添加自定义校验:

addMethodname, 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));}, "请正确填写您的邮政编码");

      

           注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建议一般写在 additional-methods.js 文件中。

        注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、数字和下划线"。调用前要添加对 additional-methods.js 文件的引用。

        10.radio 、checkbox 和 select 的验证:

        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"/>

     

        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[]" />

      

        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

0 0
原创粉丝点击