欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery validate添加自定义验证规则(验证邮箱 邮政编码)

程序员文章站 2023-11-22 10:24:28
代码如下:

代码如下:


<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>validate.js拓展验证</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript" src="validate.expand.js"></script>
</head>
<body>
<form action=""  method="get" id="tinyphp">
<input type="text" value="" name="iszipcode" />
<input type="submit" value="提交" />
</form>
<script type="text/javascript">
$("#tinyphp").validate({
    // 添加验证规则
    rules: {
        iszipcode: {    //验证邮箱
            iszipcode: true
        }
    }
}); 
    </script>
</body>
</html>

 

validate.expand.js

 

. 代码如下:


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

 

添加多个验证方法

. 代码如下:


 <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>validate.js拓展验证</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript" src="validate.expand.js"></script>
</head>
<body>
<form action=""  method="get" id="tinyphp">
邮编:<input type="text" value="" name="iszipcode" /><br /><br />

 

名字:<input type="text" value="" name="username" />
<input type="submit" value="提交" />
</form>
<script type="text/javascript">
$("#tinyphp").validate({
    // 添加验证规则
    rules: {
        iszipcode: {    //验证邮箱
            iszipcode: true
        },
        username:{
            required: true,
            username: true,
            rangelength: [5,10]   
        }
    },

    //重设提示信息,可省略
    messages:{
        username: {
            required: "请填写用户名",
            rangelength: "用户名必须在5-10个字符之间"
        }      

    }
}); 
    </script>
</body>
</html>
 

 

 validate.expand.js

 

. 代码如下:


 jquery.validator.addmethod("username", function(value, element) {
    return this.optional(element) || /^[\u0391-\uffe5\w]+$/.test(value);
}, "用户名必须在5-10个字符之间");  

 

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