插件—jquery.validate.js

前言

在学习jquery.validate.js中的一个小案例,只是这个插件的简单使用。

案例代码如下:

<head>
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.validator.addMethod("phones", function (value, element, param) { //自定义验证
                var exp = new RegExp(param);
                return this.optional(element) || exp.test(value);
            }, "不等于");
            $("#form1").validate({
                rules: {
                    Name: { required: true, maxlength: 6, minlength: 4 }, //给用户框定义规则
                    total: { equalTo: "#Name" },
                    phone: { phones: /^1[3458][0-9]{9}$/ }
                },
                messages: {
                    Name: { required: "必填项", maxlength: "大于6个字符", minlength: "少于4个字符"},//给用户框定义提示语
                    phone:{phones:"不符合规则"}
                },
                errorElement: "em",                   //给用户框自定义提示图片
                success: function (label) {
                    label.text("&nbsp").addClass("success"); //$nbsp:是为了兼容IE的
                }
            });
        });
    </script>
    <%-- 给用户框自定义提示图片 样式--%>
    <style type="text/css">
        em.error
        {
            background: url("images/1.png") no-repeat 0px 0px;
            padding-left:19px;
            color: red;
                 }
       em.success {
            background: url("images/2.png") no-repeat 0px 0px;
            padding-left:19px;
       }
    </style>
</head>
<body>
    <form id="form1">
   用户名:  <input type="text" name="Name" id="Name"/><br />
   7+8=:<input type="text" name="total" id="total"/><br/>
   手机:<input type="text" name="phone" id="phone"/><br/>
   <input type="submit" id="btnSubmit" value="确定"/>
    </form>
</body>

运行结果如下:

结束

我也是知道皮面,如果想再深入学习,推荐一篇博文:http://www.cnblogs.com/hejunrex/archive/2011/11/17/2252193.html

原文地址:https://www.cnblogs.com/zl879211310/p/3478333.html