jquery.validate学习总结

时间:2022-04-07 09:25:23

1.自定义中文消息,可以写成jquery.validate.message_cn.js与jquery.validate.js一起引用

//自定义中文消息
var cn_msg = {
    required:"必选字段",
    remote:"请修正改字段",
    email:"请输入正确格式的电子邮件",
    url:"请输入合法的网址",
    date:"请输入合法的日期",
    dateISO:"请输入合法的日期(ISO)",
    number:"请输入合法的数字",
    digits:"只能输入整数",
    creditcard:"请输入合法的信用卡账号",
    equalTo:"请再次输入相同的值",
    accept:"请输入拥有合法后缀名的字符串",//accept:"jpg|gif"
    maxlength:$.format("请输入一个长度最多是{0}的字符串"),
    minlength:$.format("请输入一个长度最少是{0}的字符串"),
    rangelength:$.format("请输入一个长度介于{0}和{1}之间的字符串"),
    range:$.format("请输入一个介于{0}和{1}之间的值"),
    max:$.format("请输入一个最大为{0}的值"),
    min:$.format("请输入一个最小为{0}的值")
};

$.extend($.validator.messages,cn_msg);

2.自定义扩展功能

jQuery(document).ready(function(){
    jQuery.validator.addMethod(
        "isMobile",
        function(value,element){
            var regex_mobile = /^1[3,5,8]\d{9}$/;
            return this.optional(element) || (regex_mobile.test(value));
        },
        "请正确填写手机号码"
    );//手机号验证
    jQuery.validator.addMethod(
        "isTel",
        function(value,element){
            var regex_tel = /^\d{3,4}-\d{7,8}$/;
            return this.optional(element) || (regex_tel.test(value));
        },
        "请输入正确的电话号码例如:0411-89898899"
    );//电话号码验证
    jQuery.validator.addMethod(
        "isIDCard",
        function(value,element){
            var regex_card15 = /^\d{14}[0-9a-zA-Z]$/;
            var regex_card18 = /^\d{17}[0-9a-zA-Z]$/;
            return this.optional(element) || (regex_card15.test(value) || regex_card18.test(value));
        },
        "请输入正确的身份证号码"
    );//身份证粗略校验
    jQuery.validator.addMethod(
        "isLN",
        function(value,element){
          var regex_val = /^[a-zA-z]\w*$/;
          return this.optional(element) || (regex_val.test(value));  
        },
        "只能为字母数字或下划线,以字母开头"
    );
    jQuery.validator.addMethod(
        "byteRangeLenth",
        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]);
        },
        jQuery.format("请确保输入的值在{0}-{1}个字节之间(一个中文算2个字节)")
    );
});


3.使用验证

1)Master页进行验证

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.Master.cs" Inherits="JSTest.Master" %>

<!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" >
<head runat="server">
    <title>Master Page</title>
    <script language="javascript" type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
    <script language="javascript" type="text/javascript" src="js/jquery.validate.min.js"></script>
    <script language="javascript" type="text/javascript" src="js/jquery.validate.message_cn.js"></script>
    <script type="text/javascript" language="javascript" src="js/MasterPage.js"></script>
    <script language="javascript" type="text/javascript">
        var opts = null;
    </script>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div style="text-align:right"><a href="Default.aspx">  主页    </a></div>
        <br />
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            Master Content
        </asp:ContentPlaceHolder>
    </div>
    </form>
    <script type="text/javascript" language="javascript">
        jQuery(document).ready(function(){
            if(opts!=undefined && opts!=null){
                jQuery("#<%=form1.ClientID %>").validate(opts);
            }
            else{
                jQuery("#<%=form1.ClientID %>").validate();    
            }
        });
    </script>
</body>
</html>

定义全局变量opts,然后在要验证页面的script中写如下代码:

opts={
    /*验证规则*/
    rules:{
        '<%=txtUserID.UniqueID %>':{required:true,isLN:true},
        '<%=txtUserName.UniqueID %>':{required:true},
        '<%=txtAge.UniqueID %>':{required:true,number:true,range:[1,99]},
        '<%=txtEmail.UniqueID %>':{required:true,email:true},
        '<%=txtMobile.UniqueID %>':{required:true,isMobile:true},
        '<%=txtPwd.UniqueID %>':{required:true,minlength:6},
        '<%=txtRePwd.UniqueID %>':{required:true,minlength:6,equalTo:"#<%=txtPwd.ClientID %>"},
        'txtDate':{required:true,dateISO:true,date:true}
    },
    /*提示信息*/
    messages:{
        '<%=txtPwd.UniqueID %>':{required:"不输入密码怎么行?",minlength:"密码太短了最少6位"},
        '<%=txtUserID.UniqueID %>':{required:"输入用户名?"},
        '<%=txtAge.UniqueID %>':{range:jQuery.format("您的年龄要在{0}-{1}之间")},
        'txtDate':{required:"日期必须要填",dateISO:"日期格式不对",date:"必须是日期"}
    },
    /* 错误信息的显示位置 */       
    errorPlacement: function(error, element){
        error.appendTo(element.parent());
    },     
    /* 验证通过时的处理 */       
    success: function(label){
        // set   as text for IE        
        label.html(" ").addClass("checked");       
    },     
    /* 获得焦点时不验证 */       
    focusInvalid: false,
    onkeyup: false    
};

在按钮submit的时候就会去做validate判断。注:因为使用了master页,所以取服务器控件的ID时用<%=ControlName.UniqueID%>。

2)验证写在方法中,可以自定义调用时间

function checkTest(){
        opts = {
            rules:{
                '<%=txtMobile.UniqueID %>':{required:true,isMobile:true}
            },
            messages:{
                '<%=txtMobile.UniqueID %>':{required:"手机号不能不输入",isMobile:"手机号需要填11位,哈哈哈"}
            }
        };
        $("#aspnetForm").data("validator", null);
        $("#aspnetForm").validate(opts);
        //$("#<%=txtIDCard.ClientID %>").rules("add",{required:true,isIDCard:true});
        $("#<%=txtIDCard.ClientID %>").rules("add",{required:true,isIDCard:true,messages:{required:"身份证必须输入",isIDCard:"身份证!!!"}});
        $("#<%=txtUserName.ClientID %>").rules("add",{required:true,byteRangeLenth:[2,10]});
        var k = $("#aspnetForm").validate().element("#<%=txtIDCard.ClientID %>"); //输出True OR False
        var x = $("#aspnetForm").validate().element("#<%=txtUserName.ClientID %>");
}
function unbind() {
    $("#aspnetForm").unbind('submit');
}

附上一个验证时候文本框CSS

<style type="text/css">
        #firstTable .labels
        {
        	text-align:right;
        }
        #firstTable .contents
        {
        	text-align:left;
        }
        label.error
        {
        	color:Red;
        	font-style:italic;
        	padding-left:20px;
        }
        input.error
        {
        	border:dashed 1px red;
        }
    </style>