jquery.validate 表单验证

项目中的表单需要封装一个组件,希望能够灵活且便捷的封装表单的验证规则和提示,选用 http://jqueryvalidation.org/

主要关注:

表单各单元关联验证规则和提示  

<input id="cname"  minlength="2"  required />  //html属性来指定规则

<input id="email" class="{validate:{required:true,email:true}}" />  //甚至支持元标签解析

不推荐使用,最好还是全部规范使用js注册规则和提示。主要是便于统一维护
$("#form").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            username: {required: true,minlength: 2},
            password: {required: true,minlength: 5},
            confirm_password: {required: true,minlength: 5,equalTo: "#password"},
            email: { required: true,email: true},
            topic: {required: "#newsletter:checked",minlength: 2},
            agree: "required"
        },
        messages: {
            firstname: "Please enter your firstname",
            lastname: "Please enter your lastname",
            username: {required: "Please enter a username",minlength: "Your username must consist of at least 2 characters"},
            password: {required: "Please provide a password",minlength: "Your password must be at least 5 characters long"},
            confirm_password: {required: "Please provide a password",minlength: "Your password must be at least 5 characters long",equalTo: "Please enter the same password as above"},
            email: "Please enter a valid email address",
            agree: "Please accept our policy"
        }
    });

自定义规则和提示  

$.validator.addMethod("规则名", function(value, element, param) {
  value     表单元素的值
  element    表单元素dom
  param     定义的值
},"自定义提示");

例:
<input id="name" maxlength="20">123</>
value=123;element=$("#name");param=20

maxlength: function( value, element, param ) {

  var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);

   return this.optional(element) || length <= param;
 }

 

 

个性化错误提示UI 

    var validator = $("#form").validate({
        errorContainer: container,
        errorLabelContainer: $("ol", container),
        wrapper: 'li',

    errorPlacement: function(error, element) {

        error.appendTo( element.parent("td").next("td") );
     }

    });

  errorContainer:  错误提示关联的全局显示dom容器,设置后出现任何错误都会显示关联的dom容器

errorLabelContainer 提示文字的容器,若设置会将错误标签只会在errorLabelContainer匹配,且不会append到表单元素后面。

若errorContainer和errorLabelContainer都设置了,每次有错误的时候会调用$(this.settings.errorContainer).add( this.settings.errorLabelContainer );将各个错误插入到全局的提示容器中,暂时来说我们页面都不会设置这2个属性。

 

wrapper:    包裹错误提示的标签,设置li后:<li><label>error</label></li>

errorElement:  错误提示的标签,默认是label

errorPlacement:  查找错误提示dom的位置方法,优先通过this.settings.errorElement + "." + errorClass查找,若无法匹配则通过errorPlacement查找,默认是直接插入错误单元后面

 

综合:错误的提示的逻辑是先查找errorContainer,有设置的化显示errorContainer提示。再查找errorLabelContainer,同时设置了errorContainer和errorLabelContainer则将errorLabelContainer的内置加到errorContainer中,若没有设置errorLabelContainer则调用errorPlacement来添加

error的位置,error的生成会调用wrapper和errorElement。

if ( !this.labelContainer.append(label).length ) {
                    if ( this.settings.errorPlacement ) {
                        this.settings.errorPlacement(label, $(element) );
                    } else {
                        label.insertAfter(element);
                    }
                }


  单提交和重置接口

$("#myform").validate({
  submitHandler: function(form) {form.submit();}
});

 var v = $("#form").validate();$(".cancel").click(function() {v.resetForm();//重置})  

本地化

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

 

                    //label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent(); @yinshen 本地化dom
                    label = label.hide().show().wrap("<" + this.settings.wrapper + " class='frm_msg fail'/>").parent().prepend("<i>●</i>");

 

 

posted on 2013-07-10 22:24  西瓜SY  阅读(1116)  评论(0编辑  收藏  举报