jQuery Validate 插件

 validate-methods.js

/*****************************************************************
 * jQuery Validate扩展验证方法  (linjq)    
 * Modified by guojunhui
 * Date modified:01/01/2017  
*****************************************************************/
$(function(){
    // 判断整数value是否等于0 
    jQuery.validator.addMethod("isIntEqZero", function(value, element) { 
         value=parseInt(value);      
         return this.optional(element) || value==0;       
    }, "整数必须为0"); 
      
    // 判断整数value是否大于0
    jQuery.validator.addMethod("isIntGtZero", function(value, element) { 
         value=parseInt(value);      
         return this.optional(element) || value>0;       
    }, "整数必须大于0"); 
      
    // 判断整数value是否大于或等于0
    jQuery.validator.addMethod("isIntGteZero", function(value, element) { 
         value=parseInt(value);      
         return this.optional(element) || value>=0;       
    }, "整数必须大于或等于0");   
    
    // 判断整数value是否不等于0 
    jQuery.validator.addMethod("isIntNEqZero", function(value, element) { 
         value=parseInt(value);      
         return this.optional(element) || value!=0;       
    }, "整数必须不等于0");  
    
    // 判断整数value是否小于0 
    jQuery.validator.addMethod("isIntLtZero", function(value, element) { 
         value=parseInt(value);      
         return this.optional(element) || value<0;       
    }, "整数必须小于0");  
    
    // 判断整数value是否小于或等于0 
    jQuery.validator.addMethod("isIntLteZero", function(value, element) { 
         value=parseInt(value);      
         return this.optional(element) || value<=0;       
    }, "整数必须小于或等于0");  
    
    // 判断浮点数value是否等于0 
    jQuery.validator.addMethod("isFloatEqZero", function(value, element) { 
         value=parseFloat(value);      
         return this.optional(element) || value==0;       
    }, "浮点数必须为0"); 
      
    // 判断浮点数value是否大于0
    jQuery.validator.addMethod("isFloatGtZero", function(value, element) { 
         value=parseFloat(value);      
         return this.optional(element) || value>0;       
    }, "浮点数必须大于0"); 
      
    // 判断浮点数value是否大于或等于0
    jQuery.validator.addMethod("isFloatGteZero", function(value, element) { 
         value=parseFloat(value);      
         return this.optional(element) || value>=0;       
    }, "浮点数必须大于或等于0");   
    
    // 判断浮点数value是否不等于0 
    jQuery.validator.addMethod("isFloatNEqZero", function(value, element) { 
         value=parseFloat(value);      
         return this.optional(element) || value!=0;       
    }, "浮点数必须不等于0");  
    
    // 判断浮点数value是否小于0 
    jQuery.validator.addMethod("isFloatLtZero", function(value, element) { 
         value=parseFloat(value);      
         return this.optional(element) || value<0;       
    }, "浮点数必须小于0");  
    
    // 判断浮点数value是否小于或等于0 
    jQuery.validator.addMethod("isFloatLteZero", function(value, element) { 
         value=parseFloat(value);      
         return this.optional(element) || value<=0;       
    }, "浮点数必须小于或等于0");  
    
    // 判断浮点型  
    jQuery.validator.addMethod("isFloat", function(value, element) {       
         return this.optional(element) || /^[-\+]?\d+(\.\d+)?$/.test(value);       
    }, "只能包含数字、小数点等字符"); 
     
    // 匹配integer
    jQuery.validator.addMethod("isInteger", function(value, element) {       
         return this.optional(element) || (/^[-\+]?\d+$/.test(value) && parseInt(value)>=0);       
    }, "匹配integer");  
     
    // 判断数值类型,包括整数和浮点数
    jQuery.validator.addMethod("isNumber", function(value, element) {       
         return this.optional(element) || /^[-\+]?\d+$/.test(value) || /^[-\+]?\d+(\.\d+)?$/.test(value);       
    }, "匹配数值类型,包括整数和浮点数");  
    
    // 只能输入[0-9]数字
    jQuery.validator.addMethod("isDigits", function(value, element) {       
         return this.optional(element) || /^\d+$/.test(value);       
    }, "只能输入0-9数字");  
    
    // 判断中文字符 
    jQuery.validator.addMethod("isChinese", function(value, element) {       
         return this.optional(element) || /^[\u0391-\uFFE5]+$/.test(value);       
    }, "只能包含中文字符。");   
 
    // 判断英文字符 
    jQuery.validator.addMethod("isEnglish", function(value, element) {       
         return this.optional(element) || /^[A-Za-z]+$/.test(value);       
    }, "只能包含英文字符。");   
 
     // 手机号码验证    
    jQuery.validator.addMethod("isMobile", function(value, element) {    
      var length = value.length;    
      return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(15[0-35-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(value));    
    }, "手机号码格式不正确。");

    // 电话号码验证    
    jQuery.validator.addMethod("isPhone", function(value, element) {    
      var tel = /^(\d{3,4}-?)?\d{7,9}$/g;    
      return this.optional(element) || (tel.test(value));    
    }, "电话号码格式不正确");

    // 联系电话(手机/电话皆可)验证   
    jQuery.validator.addMethod("isTel", function(value,element) {   
        var length = value.length;   
        var mobile = /^(((13[0-9]{1})|(15[0-35-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        var tel = /^(\d{3,4}-?)?\d{7,9}$/g;       
        return this.optional(element) || tel.test(value) || (length==11 && mobile.test(value));   
    }, "请输入正确手机号码或电话号码"); 
 
     // 匹配qq      
    jQuery.validator.addMethod("isQq", function(value, element) {       
         return this.optional(element) || /^[1-9]\d{4,12}$/;       
    }, "QQ号码不合法");   
 
     // 邮政编码验证    
    jQuery.validator.addMethod("isZipCode", function(value, element) {    
      var zip = /^[0-9]{6}$/;    
      return this.optional(element) || (zip.test(value));    
    }, "邮政编码不正确");  
    
    // 匹配密码,以字母开头,长度在6-16之间,只能包含字符、数字和下划线。      
    jQuery.validator.addMethod("isPwd", function(value, element) {       
         return this.optional(element) || /^[a-zA-Z]\\w{6,16}$/.test(value);       
    }, "以字母开头,长度在6-12之间,只能包含字符、数字和下划线。");  
    
    // 身份证号码验证
    jQuery.validator.addMethod("isIdCardNo", function(value, element) { 
      //var idCard = /^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\w)$/;   
      return this.optional(element) || isIdCardNo(value);    
    }, "身份证号码不正确"); 

    // IP地址验证   
    jQuery.validator.addMethod("ip", function(value, element) {    
      return this.optional(element) || /^(([1-9]|([1-9]\d)|(1\d\d)|(2([0-4]\d|5[0-5])))\.)(([1-9]|([1-9]\d)|(1\d\d)|(2([0-4]\d|5[0-5])))\.){2}([1-9]|([1-9]\d)|(1\d\d)|(2([0-4]\d|5[0-5])))$/.test(value);    
    }, "请填写正确的IP地址");
   
    // 字符验证,只能包含中文、英文、数字、下划线等字符。    
    jQuery.validator.addMethod("stringCheck", function(value, element) {       
         return this.optional(element) || /^[a-zA-Z0-9\u4e00-\u9fa5-_]+$/.test(value);       
    }, "只能包含中文、英文、数字、下划线等字符");   
   
    // 匹配english  
    jQuery.validator.addMethod("isEnglish", function(value, element) {       
         return this.optional(element) || /^[A-Za-z]+$/.test(value);       
    }, "必须输入英文");   
    
    // 匹配汉字  
    jQuery.validator.addMethod("isChinese", function(value, element) {       
         return this.optional(element) || /^[\u4e00-\u9fa5]+$/.test(value);       
    }, "只能输入汉字");   
    
    // 匹配中文(包括汉字和字符) 
    jQuery.validator.addMethod("isChineseChar", function(value, element) {       
         return this.optional(element) || /^[\u0391-\uFFE5]+$/.test(value);       
    }, "匹配中文(包括汉字和字符) "); 
      
    // 判断是否为合法字符(a-zA-Z0-9-_)
    jQuery.validator.addMethod("isRightfulString", function(value, element) {       
         return this.optional(element) || /^[A-Za-z0-9_-]+$/.test(value);       
    }, "判断是否为合法字符(a-zA-Z0-9-_)");   
    
    // 判断是否包含中英文特殊字符,除英文"-_"字符外
    jQuery.validator.addMethod("isContainsSpecialChar", function(value, element) {  
         var reg = RegExp(/[(\ )(\`)(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\+)(\=)(\|)(\{)(\})(\')(\:)(\;)(\')(',)(\[)(\])(\.)(\<)(\>)(\/)(\?)(\~)(\!)(\@)(\#)(\¥)(\%)(\…)(\&)(\*)(\()(\))(\—)(\+)(\|)(\{)(\})(\【)(\】)(\‘)(\;)(\:)(\”)(\“)(\’)(\。)(\,)(\、)(\?)]+/);   
         return this.optional(element) || !reg.test(value);       
    }, "含有中英文特殊字符");
    
    //车牌号校验
    jQuery.validator.addMethod("isPlateNo", function(value, element) {
        var reg = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/;
        return this.optional(element) || (tel.test(value)); 
    },"请输入正确车牌号");
});
//身份证号码的验证规则
function isIdCardNo(num){ 
    //if (isNaN(num)) {alert("输入的不是数字!"); return false;} 
   var len = num.length, re; 
   if (len == 15) 
   re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{2})(\w)$/); 
   else if (len == 18) 
   re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\w)$/); 
   else {
        //alert("输入的数字位数不对。"); 
        return false;
    } 
   var a = num.match(re); 
   if (a != null) 
   { 
   if (len==15) 
   { 
   var D = new Date("19"+a[3]+"/"+a[4]+"/"+a[5]); 
   var B = D.getYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5]; 
   } 
   else 
   { 
   var D = new Date(a[3]+"/"+a[4]+"/"+a[5]); 
   var B = D.getFullYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5]; 
   } 
   if (!B) {
        //alert("输入的身份证号 "+ a[0] +" 里出生日期不对。"); 
        return false;
    } 
   } 
   if(!re.test(num)){
        //alert("身份证最后一位只能是数字和字母。");
        return false;
    }
   return true; 
}

 

messages_zh.js

(function( factory ) {
    if ( typeof define === "function" && define.amd ) {
        define( ["jquery", "../jquery.validate"], factory );
    } else {
        factory( jQuery );
    }
}(function( $ ) {

/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
 */
$.extend($.validator.messages, {
    required: "这是必填字段",
    remote: "请修正此字段",
    email: "请输入有效的电子邮件地址",
    url: "请输入有效的网址",
    date: "请输入有效的日期",
    dateISO: "请输入有效的日期 (YYYY-MM-DD)",
    number: "请输入有效的数字",
    digits: "只能输入数字",
    creditcard: "请输入有效的信用卡号码",
    equalTo: "你的输入不相同",
    extension: "请输入有效的后缀",
    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} 的数值")
});

}));

 

引用 js 库

<script type="text/javascript" src="jquery.validation/1.14.0/jquery.validate.js">script>
<script type="text/javascript" src="jquery.validation/1.14.0/validate-methods.js">script>
<script type="text/javascript" src="jquery.validation/1.14.0/messages_zh.js">script>

 

type="submit"   提交方式:

<form class="form form-horizontal" id="formLogin" name="formLogin">
    <div class="row cl">
        <label class="form-label col-xs-3"><i class="Hui-iconfont">i>label>
        <div class="formControls col-xs-8">
            <input id="UserName" name="UserName" type="text" placeholder="用户名" class="input-text size-L">
        div>
    div>
    <div class="row cl">
        <label class="form-label col-xs-3"><i class="Hui-iconfont">i>label>
        <div class="formControls col-xs-8">
            <input id="Password" name="Password" type="password" placeholder="密码" class="input-text size-L">
        div>
    div>
    <div class="row cl">
        <div class="formControls col-xs-8 col-xs-offset-3">
            <input id="ValidateCode" name="ValidateCode" class="input-text size-L" type="text" placeholder="验证码" onblur="if(this.value==''){this.value='验证码'}" onclick="if(this.value=='验证码'){this.value='';}" value="验证码" style="width:150px;">
            <img src="~/WebAdmin/CreateValidateCode" id="imgValidateCode" class=""> <a id="kanbuq" href="javascript:;">看不清,换一张a>
        div>
    div>
    <div class="row cl">
        <div class="formControls col-xs-8 col-xs-offset-3 c-error" id="tips">
            <div class="validateMsg">div>
        div>
    div>
    <div class="row cl">
        <div class="formControls col-xs-8 col-xs-offset-3">
            <input name="" id="btnLogin" type="submit" class="btn btn-success radius size-L mr-15" value=" 登    录 ">
            <input name="" type="reset" class="btn btn-default radius size-L" value=" 取    消 ">
        div>
    div>
form>


$("#formLogin").validate({
    rules: {
        UserName: {
            required: true
        },
        Password: {
            required: true
        },
        ValidateCode: {
            required: true,
            minlength: 4,
            maxlength: 4
        }
    },
    messages: {
        UserName: "用户名不能为空;",
        Password: "密码不能为空;",
        ValidateCode: {
            required: "验证码不能为空;",
            minlength: "输入验证码长度有误;",
            maxlength: "输入验证码长度有误;",
        }
    },
    onkeyup: false,
    focusCleanup: true,
    success: "valid",
    errorLabelContainer: $("#tips .validateMsg"),    //统一显示在哪里
    errorElement: "span",   //错误信息用什么标签包裹
    submitHandler: function (form) {
        $(form).ajaxSubmit({
            url: "/WebAdmin/Login",
            dataType: "json",
            type: "post",
            success: function (res) {
                if (res.status == "ok") {
                    //alert("登录成功");
                    location.href = "/WebAdmin/";
                }
                else {
                    //alert("错误:" + res.errorMsg);
                    $("#tips").html(res.errorMsg);
                    $imgValidateCode.click();
                }
            },
            error: function () {
                //alert("网络出错");
                $("#tips").text("网络出错");
                $imgValidateCode.click();
            }
        });
    }
});


type="button" 提交方式:
<form class="form form-horizontal" id="formLogin" name="formLogin">
    <div class="row cl">
        <label class="form-label col-xs-3"><i class="Hui-iconfont">i>label>
        <div class="formControls col-xs-8">
            <input id="UserName" name="UserName" type="text" placeholder="用户名" class="input-text size-L">
        div>
    div>
    <div class="row cl">
        <label class="form-label col-xs-3"><i class="Hui-iconfont">i>label>
        <div class="formControls col-xs-8">
            <input id="Password" name="Password" type="password" placeholder="密码" class="input-text size-L">
        div>
    div>
    <div class="row cl">
        <div class="formControls col-xs-8 col-xs-offset-3">
            <input id="ValidateCode" name="ValidateCode" class="input-text size-L" type="text" placeholder="验证码" onblur="if(this.value==''){this.value='验证码'}" onclick="if(this.value=='验证码'){this.value='';}" value="验证码" style="width:150px;">
            <img src="~/WebAdmin/CreateValidateCode" id="imgValidateCode" class=""> <a id="kanbuq" href="javascript:;">看不清,换一张a>
        div>
    div>
    <div class="row cl">
        <div class="formControls col-xs-8 col-xs-offset-3 c-error" id="tips">
            <div class="validateMsg">div>
        div>
    div>
    <div class="row cl">
        <div class="formControls col-xs-8 col-xs-offset-3">
            <input name="" id="btnLogin" type="button" class="btn btn-success radius size-L mr-15" value=" 登    录 ">
            <input name="" type="reset" class="btn btn-default radius size-L" value=" 取    消 ">
        div>
    div>
form>

 

$("#formLogin").validate({
        rules: {
            UserName: {
                required: true
            },
            Password: {
                required: true
            },
            ValidateCode: {
                required: true,
                minlength: 4,
                maxlength: 4
            }
        },
        messages: {
            UserName: "用户名不能为空;",
            Password: "密码不能为空;",
            ValidateCode: {
                required: "验证码不能为空;",
                minlength: "输入验证码长度有误;",
                maxlength: "输入验证码长度有误;",
            }
        },
        onkeyup: false,
        focusCleanup: true,
        success: "valid",
        errorLabelContainer: $("#tips .validateMsg"),
        errorElement: "span"
    });
    

$("#btnLogin").click(function () {
    var flag = $("#formLogin").valid();
    if (!flag) {
        //没有通过验证
        return;
    }

    var formData = $("#formLogin").serializeArray();
    $.ajax({
        url: "/WebAdmin/Login", dataType: "json", type: "post", data: formData,
        success: function (res) {
            if (res.status == "ok") {
                //alert("登录成功");
                location.href = "/WebAdmin/";
            }
            else {
                //alert("错误:" + res.errorMsg);
                $("#tips").html("错误:" + res.errorMsg);
                $imgValidateCode.click();
            }
        },
        error: function () {
            //alert("网络出错");
            $("#tips").text("网络出错");
            $imgValidateCode.click();
        }
    });
});

 

参考资料:

http://www.runoob.com/jquery/jquery-plugin-validate.html

jquery.validate不使用submit提交,而是使用button按钮提交,以及使用ajax验证用户名

jquery validate让普通按钮触发表单验证

 

转载于:https://www.cnblogs.com/linyongqin/articles/7674834.html

你可能感兴趣的:(jQuery Validate 插件)