利用jQuery.validator来做表单验证,不要太轻松(全攻略)

1、介绍

jQuery.validator是给我们用来做表单验证提交时的一个插件,你可以直接去官网下载,也可以通过菜鸟教程学习和下载该插件

菜鸟教程(jQuery.validator)

2、使用

2.1下载完成后引入相应的js库

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>

2.2引入之后,在js文件中加载jQuery.validator,设置默认方式

$(document).ready(function(){
	$.validator.setDefaults({       
		  submitHandler: function(form) {    
		 		form.submit();    
		}       
	});
});

2.3对错误提示信息的标签进行css修改:

/** 表单验证 样式布局 */
label.error {
	position: absolute;
	right: 18px;
	top: 5px;
	color: #ef392b;
	font-size: 12px;
	z-index: 3;
}

默认提示用的是lable标签,在发生错误时(也就是验证没通过时)会在错误元素后追加lable标签,错误信息写在lable里面的,我们最好改造一下,错误标签的class是error,最好设置z-index高一点,因为如果不设置大一点,可能会被遮挡住,因为我们用一些其他input插件时可能样式是层叠的,这样就会挡住。这个是全局的。

局部如果不满意:也可以调,比如我要调整class为append-input的div的里面错误提示的效果

.append-input .error{
	z-index: 3;
	margin-right: 25px;
}

2.4验证表单数据:之前加载了默认方式之后,我们就可以进行验证了,看下代码

$("#form-customer-add").validate({
        rules: {
            loginAccountName: {
                accountExtend: "autoCreatAccountAndPassword",
                remote: {
                    url: ctx + "vip/customer/checkLoginAccount",
                    type: "post",
                    dataType: "json",
                    cache:false,
                    async:false,
                    data: {
                        loginAccountName: function () {
                            return $.trim($("#loginAccountName").val());
                        }
                    },
                    dataFilter: function (data, type) {
                        var result = JSON.parse(data);
                        if (result.code == 0) return true;
                        else return false;
                    }
                }
            },
            password: {
                passwordExtend:true,
                required:true
            },
            nickname:{
                required:true,
                nicknameExtend:true
            },
            telephones:{
                required:true,
                telephoneExtend:true,
                inputUniquenessExtend:["telephones","该手机号已经输入过了"],
                checkUniquenessExtend:["telephone",ctx + "vip/customer/checkPhone","手机号已经存在"]
            },
            emails:{
                emilExtend:true
            },
            trueName:{
                chineseAndLetterExtend:true,
                minlength:2
            },
            idNumber:{
                idNumberExtend:true
            },
            company:{
                numberExtend:"other"
            },
            job:{
                numberExtend:"other"
            },
            income:{
                numberExtend:true
            },
            homeAddress:{
                numberExtend:"other",
                letterExtend:"other"
            }
        },
        messages: {
            loginAccountName:{
                remote:"该账户已经被注册"
            }
        },
        errorPlacement:function(error,element) {
            error.insertAfter(element);
        },
        submitHandler: function (form) {
            add();
        }
    });

    function add() {

        var data = getFormDateReturnForm("form-customer-add");//得到表单数据

        var avatarFile = $("input[name ='avatarFile']")[0].files[0];
        data.append("avatarFile", avatarFile);

        /*-------------------获得爱好-------------------------*/
        var hobbyStr = $('#hobbys').val();//获取爱好的值
        if(!isEmptyForString(hobbyStr)){
            var hobbys = hobbyStr.split(",");//得到爱好数组
            data.append("hobbys",hobbys);
        }

        /*-------------------获得车品牌/车系/车型---------------------------*/
        var carsObj = $("span[name='cars']");
        if(!isEmptyForObject(carsObj)){
            var cars = new Array();
            $("span[name='cars']").each(function(){
                cars.push($(this).text());
            });
            data.append("cars",cars);
        }

        /*-------------------获得车牌---------------------------*/
        var carLicensesObj = $("span[name='carLicensesSpan']");
        if(!isEmptyForObject(carLicensesObj)){
            var carLicenses = new Array();
            $("span[name='carLicensesSpan']").each(function(){
                cars.push($(this).text());
            });
            data.append("carLicenses",carLicenses);
        }

        $.ajax({
            cache: true,
            type: "POST",
            url: ctx + "vip/customer/add",
            data: data,
            contentType: false,
            processData: false,
            mimeType: "multipart/form-data",
            async: false,
            error: function (request) {
                $.modal.alertError("系统错误");
            },
            success: function (data) {
                $.operate.saveSuccess(JSON.parse(data));
            }
        });
    }

代码太长,我们拆分解释:

(1)

$("#form-customer-add").validate({

这个表示的是加载你的form表单的id

<form class="form-horizontal m" id="form-customer-add">

(2)

$("#form-customer-add").validate({
        rules: {

rules表示返回元素的验证规则,意思就是说我们验证规则都写在这里面

(3)

$("#form-customer-add").validate({
        rules: {
            loginAccountName: {

loginAccountName 表示的是我们自己表单中元素的name值,说明一下,jQuery.validator验证匹配是按照name来进行匹配的

<div class="form-group">
    <label class="col-sm-3 control-label ">用户账号:</label>
    <div class="col-sm-8">
        <input class="form-control" type="text" id="loginAccountName" name="loginAccountName" placeholder="请填写用户账号"/>
    </div>
</div>

(4)

$("#form-customer-add").validate({
        rules: {
            loginAccountName: {
                accountExtend: "autoCreatAccountAndPassword",
                remote: {

accountExtend 表示的是我们自己定义的验证规则,remote是插件提供的向后台发送请求验证的规则

(4.1)romote的使用

remote: {
      url: ctx + "vip/customer/checkLoginAccount",
      type: "post",
      dataType: "json",
      cache:false,
      async:false,
      data: {
          loginAccountName: function () {
                return $.trim($("#loginAccountName").val());
          }
      },
      dataFilter: function (data, type) {
          var result = JSON.parse(data);
          if (result.code == 0) return true;
          else return false;
      }
}

说明一下,这个使用时加入 async:false表示同步请求,true或者不加这个属性表示异步请求

data表示你要传入到后台的数据,里面的键值对形式的参数表示后台接受参数的名字和值,这个值是个方法,返回的就是你要传入后台的值,类似于{loginAccount:"test12345"}这种形式

dataFileter表示的是你返回的信息,data是后台返回的数据,自己做判定,最后该函数返回true表示通过验证,false表示没有通过验证,提示错误信息。

这里就直接说明messages的作用吧,就是验证没有通过的错误提示信息,这个跟rules同级

看这段代码:

messages: {
     loginAccountName:{
           remote:"该账户已经被注册"
     }
}

messages里面的结构和rules里面的层级结构是一样的,没有顺序之分,可选择性指定提示信息

因为插件自带的一些验证方法,包含默认提示信息,如果你想用自己的提示信息,直接这样指定就可了

(4.2自定义验证规则)

自定义验证规则

上面已经提到了accountExtend是我们自己定义的验证规则

自定义验证规则必须调用addMethod方法

举例:

jQuery.validator.addMethod("passwordExtend", function (value, element) {
        var length = value.length;
        return this.optional(element) || (FormVerifyRegEx.letterAndNumber.test(value) && length >= 8 && length <= 20);
    }, "<i class='fa fa-times-circle'>密码必须为8-12位字母和数字组合</i>");

第一个参数:自定义规则名字

passwordExtend 是我们为自定义规则取的名字

第二个参数是一个方法,最重要(有三个参数):

value表示的是聚焦的输入框的值,我们要验证的就是这个值

element表示的是当前聚焦的节点元素

还有个参数params,表示你传递进来的参数,传递一个参数直接写就是了,多参数用数组[],这个也可以不写

第三个参数表示错误的提示信息:这个提示信息写在这里不能是动态的,只能是死的

提示:方法内部返回false表示没有通过验证,true表示通过验证,方法内部规则自己随意写,保证返回就行了

this.optional(element) 表示可以为空值

调用:传入true就会默认调用了,false就不会调用;required是该插件内置的验证规则,表示不能为空,false就不会调用,true就会调用,你不写也不会调用

$("#form-customer-add").validate({
        rules: {
            password: {
                passwordExtend:true,
                required:true
            }
        }
)};

看下另一个例子:

/**
     * 验证数字
     * 传入true表示必须是数字,
     * "false"输入内容不能包含数字,
     * "other"表示是输入内容不能全是数字
     */
    $.validator.addMethod("numberExtend", function (value, element, params) {
        console.log(params);
        if (params === true) {
            $.validator.messages.numberExtend = "<i class='fa fa-times-circle'>输入内容必须是0-9数字</i>";
            return this.optional(element) || (FormVerifyRegEx.number.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.number.test(value.substr(i,1))){
                    $.validator.messages.numberExtend = "<i class='fa fa-times-circle'>输入内容不能包含数字</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.numberExtend = "<i class='fa fa-times-circle'>输入内容不能全是数字</i>";
        return this.optional(element) || !(FormVerifyRegEx.number.test(value));
    });

这个是另一种写法,说明一下:

$.validator.messages.numberExtend  表示根据情况动态修改错误提示信息,这里的numberExtend  要和第一个参数你定义的规则名一样

你也看到了,为什么我接收false用了“”,这里就有个关键了,如果传值为false,是不会调用这个验证规则的,所以你必须写成其他形式的参数,true可以传递进来也能拿到,默认写true就表示调用这个验证方法

调用:

company:{
     numberExtend:"other"
},

写到这里,其实我们需要的配置基本就完了,说明一下,其他不用配置用默认的就行,关于select、和redio看菜鸟教程就行了,没什么讲的,在标签上写上几个属性就可以了,自己去参考

errorPlacement:function(error,element) {
            error.insertAfter(element);
        },
submitHandler: function (form) {
            add();
        }

这个呢,errorPlacement 表示错误信息放在那里,默认就是我写的这个,追加在元素后面,不过这个我们不用去指定,删除就是了,

submitHandler 表示的是验证全部通过后执行的函数,点击type为submit的按钮自动触发这个函数,当我们点击提交后验证通过就会触发这个函数,

<button type="submit" class="btn btn-primary">提交</button>

add()就是我们自己写的向后台发送数据的方法了

说明:在验证的时候,我们写在同一个name里面的验证规则是从上至下依次执行了,一旦上面的验证没有通过,下面的验证也就不会继续验证,上面的验证通过后继续下面的验证

homeAddress:{
       numberExtend:"other",
       letterExtend:"other"
}

像这样,先执行numberExtend验证,再执行letterExtend验证,所有的验证规则都可以结合起来使用

解决相同name元素只验证第一个的问题

/**
 * 解决jquery表单验证name值相同只验证第一个的问题
 */
$(function () {
    function jqueryVerify() {
        if ($.validator) {
            $.validator.prototype.elements = function () {
                var validator = this,
                    rulesCache = {};
                // Select all valid inputs inside the form (no submit or reset buttons)
                return $(this.currentForm)
                    .find("input, select, textarea, [contenteditable]")
                    .not(":submit, :reset, :image, :disabled")
                    .not(this.settings.ignore)
                    .filter(function () {
                        var name = this.id || this.name || $(this).attr("name"); // For contenteditable
                        if (!name && validator.settings.debug && window.console) {
                            console.error("%o has no name assigned", this);
                        }
                        // Set form expando on contenteditable
                        if (this.hasAttribute("contenteditable")) {
                            this.form = $(this).closest("form")[0];
                        }
                        // Select only the first element for each name, and only those with rules specified
                        if (name in rulesCache || !validator.objectLength($(this).rules())) {
                            return false;
                        }
                        rulesCache[name] = true;
                        return true;
                    });
            }
        }
    }

    jqueryVerify();
});

最后福利时间,我写了个完整的地验证规则,大部分都能直接使用:

通用js,内置一些常用方法:common.js

//获得项目名称
function getPath() {
	var pathName = window.document.location.pathname;
	var projectName = pathName
			.substring(0, pathName.substr(1).indexOf('/') + 1);
	return projectName;
}

// 动态给Date对象添加新的方法
Date.prototype.formatDateTime = function() {
	var y = this.getFullYear();
	var m = this.getMonth() + 1;
	var d = this.getDate();
	var hh = this.getHours();
	var mm = this.getMinutes();
	var ss = this.getSeconds();
	return y + "-" + formatNumber(m) + "-" + formatNumber(d) + " "
			+ formatNumber(hh) + ":" + formatNumber(mm) + ":"
			+ formatNumber(ss);
}

// 动态给Date对象添加新的方法
Date.prototype.formatDate = function() {
	var y = this.getFullYear();
	var m = this.getMonth() + 1;
	var d = this.getDate();
	return y + "-" + formatNumber(m) + "-" + formatNumber(d);
}

// 位数不够,就使用0补位
function formatNumber(value) {
	if (value < 10) {
		value = '0' + value;
	}
	return value;
}

/**
 * 判断字符串是否为空
 * 
 * @param string
 * @returns
 */
function isEmptyForString(string) {
	if (string === null || string === "" || string === undefined) {
		return true;
	}
	return false;
}

/**
 * 判断对象是否为空
 * 
 * @param object
 * @returns
 */
function isEmptyForObject(object) {
	if (object === null || object === undefined) {
		return true;
	}
	return false;
}

// 拿到表单中的数据,返回类对象
function getFormData(id) {
	var d = {};
	var t = $('#' + id).serializeArray();
	$.each(t, function() {
		d[this.name] = this.value;
	});
	return d;
}

//拿到表单中的数据,返回表单对象
function getFormDateReturnForm(id) {
	var form = new FormData();
	var t = $('#' + id).serializeArray();
	$.each(t, function() {
		form.append(this.name,this.value);
	});
	return form;
}

//重置表单,刷新表格数据
function formReset(formName){
	document.getElementById(formName).reset();
	$.table.search(formName);//我这里是用的bootstrap,所以这个是刷新表格的,上面的是重置表单
}

function getAge2Birth(str) {
	var strBirthday = str.split(" ");
	var returnAge;
	var strBirthdayArr = strBirthday[0].split("-");
	var birthYear = strBirthdayArr[0];
	var birthMonth = strBirthdayArr[1];
	var birthDay = strBirthdayArr[2];

	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1;
	var nowDay = d.getDate();

	if (nowYear == birthYear) {
		returnAge = 0;// 同年 则为0岁
	} else {
		var ageDiff = nowYear - birthYear; // 年之差
		if (ageDiff > 0) {
			if (nowMonth == birthMonth) {
				var dayDiff = nowDay - birthDay;// 日之差
				if (dayDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			} else {
				var monthDiff = nowMonth - birthMonth;// 月之差
				if (monthDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			}
		} else {
			returnAge = -1;// 返回-1 表示出生日期输入错误 晚于今天
		}
	}
	return returnAge;// 返回周岁年龄
}

function getDate(dateStr){
	var str = dateStr.split(" ");
	var strArr = str[0].split("-");
	var Year = strArr[0];
	var Month = strArr[1];
	var Day = strArr[2];
	return new Date(Year,Month,Day);
}

function getNowDate(){
	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1;
	var nowDay = d.getDate();
	return nowYear + "-" + formatNumber(nowMonth) + "-" + formatNumber(nowDay);
}

/* min<=取值<=max*/
function getRandomNum(min,max)
{
	var Range = max - min;
	var Rand = Math.random();
	return (min + Math.round(Rand * Range));
}

自定义验证规则:form-verify.js

/**
 * 定义正则表达式验证规则
 * @type {{plane: RegExp, electricVehicleLicence: RegExp, idCard: RegExp, licencePlate: RegExp, telephone: RegExp, url: RegExp, chinese: RegExp, number: RegExp, dateIso: RegExp, chineseAndLetterAndNumber: RegExp, letterAndNumber: RegExp, letter: RegExp, email: RegExp}}
 */
var FormVerifyRegEx = {
    //匹配中文
    chinese: /^[\u4e00-\u9fa5]{0,}$/,
    //匹配字母
    letter: /^[a-zA-Z]*$/,
    //匹配数字
    number: /^[0-9]*$/,
    //匹配字母和数字
    letterAndNumber: /^[a-zA-Z0-9]*$/,
    //匹配中文和字母
    chineseAndLetter: /^[\u4e00-\u9fa5a-zA-Z]+$/,
    //匹配中文字母和数字
    chineseAndLetterAndNumber: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
    //匹配中文字母数字和下划线
    chineseAndLetterAndNumberAndUnder: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/,
    //匹配中文字母数字和下划线和短横线
    chineseAndLetterAndNumberAndLine:/^[\u4e00-\u9fa5a-zA-Z0-9_\-]+$/,
    //匹配手机号
    telephone: /^1[34578]\d{9}$/,
    //匹配座机号
    plane: /^(0\d{2,3}-)?\d{7,8}$/g,
    //匹配电子邮箱
    email: /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/,
    //匹配身份证
    idCard: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
    //匹配传统汽车牌照
    licencePlate: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
    //匹配电动车牌照
    electricVehicleLicence: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF][A-HJ-NP-Z0-9][0-9]{4}))$/,
    //匹配url
    url: /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i,
    //匹配日期格式(yy-MM-dd)
    dateIso: /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/
};

/**
 * 向jquery表单验证追加验证方法
 */
$(function () {

    /**
     * 验证6-12位账号
     * 传入true,表示开启验证
     */
    jQuery.validator.addMethod("accountExtend", function (value, element, params) {
        var length = value.length;
        return (FormVerifyRegEx.letterAndNumber.test(value) && length >= 6 && length <= 12);
    }, "<i class='fa fa-times-circle'>账号必须为6-12位字母和数字组合</i>");

    /**
     * 验证密码
     * 传入true,表示开启验证
     */
    jQuery.validator.addMethod("passwordExtend", function (value, element) {
        var length = value.length;
        return this.optional(element) || (FormVerifyRegEx.letterAndNumber.test(value) && length >= 8 && length <= 20);
    }, "<i class='fa fa-times-circle'>密码必须为8-12位字母和数字组合</i>");

    /**
     * 验证昵称
     * 传入true,表示开启验证
     */
    jQuery.validator.addMethod("nicknameExtend", function (value, element) {
        var chineseAndOtherLength = 0;
        var numberAndLetter = 0;
        for(var i=0;i<value.length;i++){
            if(FormVerifyRegEx.number.test(value.substr(i,1)) || FormVerifyRegEx.letter.test(value.substr(i,1))){
                numberAndLetter++;
            }else {
                chineseAndOtherLength++;
            }
        }
        var length = chineseAndOtherLength + numberAndLetter/2;
        return this.optional(element) ||  (length >= 1 && length <=20);
    }, "<i class='fa fa-times-circle'>昵称必须在1-20个中文,1个符号相当于1个中文,2个数字/英文相当于1个中文</i>");

    /**
     * 验证汽车牌照
     * 传入true,表示开启验证
     */
    jQuery.validator.addMethod("licenceExtend", function (value, element) {
        var length = value.length;
        return this.optional(element) || (FormVerifyRegEx.licencePlate.test(value)) || (FormVerifyRegEx.electricVehicleLicence.test(value));
    }, "<i class='fa fa-times-circle'>汽车牌照格式输入错误</i>");


    /**
     * 验证数字
     * 传入true表示必须是数字,
     * "false"输入内容不能包含数字,
     * "other"表示是输入内容不能全是数字
     */
    $.validator.addMethod("numberExtend", function (value, element, params) {
        console.log(params);
        if (params === true) {
            $.validator.messages.numberExtend = "<i class='fa fa-times-circle'>输入内容必须是0-9数字</i>";
            return this.optional(element) || (FormVerifyRegEx.number.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.number.test(value.substr(i,1))){
                    $.validator.messages.numberExtend = "<i class='fa fa-times-circle'>输入内容不能包含数字</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.numberExtend = "<i class='fa fa-times-circle'>输入内容不能全是数字</i>";
        return this.optional(element) || !(FormVerifyRegEx.number.test(value));
    });

    /**
     * 验证中文
     * 传入true表示必须是中文,
     * "false" 表示是输入内容不能包含中文,
     * "other" 表示是输入内容不能全是中文
     */
    $.validator.addMethod("chineseExtend", function (value, element, params) {
        if (params === true) {
            $.validator.messages.chineseExtend = "<i class='fa fa-times-circle'>输入内容必须是中文</i>";
            return this.optional(element) || (FormVerifyRegEx.chinese.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.chinese.test(value.substr(i,1))){
                    $.validator.messages.chineseExtend = "<i class='fa fa-times-circle'>输入内容不能包含中文</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.chineseExtend = "<i class='fa fa-times-circle'>输入内容不能全是中文</i>";
        return this.optional(element) || !(FormVerifyRegEx.chinese.test(value));
    });

    /**
     * 验证英文字母
     * 传入true表示必须是字母,
     * "false"表示输入内容不能包含英文字母,
     * "other"表示输入内容不能是纯字母
     */
    $.validator.addMethod("letterExtend", function (value, element, params) {
        if (params === true) {
            $.validator.messages.letterExtend = "<i class='fa fa-times-circle'>输入内容必须是英文字母</i>";
            return this.optional(element) || (FormVerifyRegEx.letter.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.letter.test(value.substr(i,1))){
                    $.validator.messages.letterExtend = "<i class='fa fa-times-circle'>输入内容不能包含英文字母</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.letterExtend = "<i class='fa fa-times-circle'>输入内容不能全是英文字母</i>";
        return this.optional(element) || !(FormVerifyRegEx.letter.test(value));
    });

    /**
     * 验证字母、数字
     * 传入true表示必须是字母、数字,
     * "false"表示输入内容不能包含数字或字母,
     * "other" 表示是输入内容除了包含数字或字母,还必须包含额外字符
     */
    $.validator.addMethod("letterAndNumberExtend", function (value, element, params) {
        if (params === true) {
            $.validator.messages.letterAndNumberExtend = "<i class='fa fa-times-circle'>输入内容必须是字母、数字</i>";
            return this.optional(element) || (FormVerifyRegEx.letterAndNumber.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.letterAndNumber.test(value.substr(i,1))){
                    $.validator.messages.letterAndNumberExtend = "<i class='fa fa-times-circle'>输入内容不能包含数字或字母</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.letterAndNumberExtend = "<i class='fa fa-times-circle'>输入内容除了包含数字或字母,还必须包含额外字符</i>";
        return this.optional(element) || !(FormVerifyRegEx.letterAndNumber.test(value));
    });


    /**
     * 验证字母、中文
     * 传入true表示必须是字母、中文,
     * "false"表示输入内容不能包含字母或中文,
     * "other"表示是除了包含字母或中文,还必须包含额外字符
     */
    $.validator.addMethod("chineseAndLetterExtend", function (value, element, params) {
        if (params === true) {
            $.validator.messages.chineseAndLetterExtend = "<i class='fa fa-times-circle'>输入内容必须是字母、中文</i>";
            return this.optional(element) || (FormVerifyRegEx.chineseAndLetter.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.chineseAndLetter.test(value.substr(i,1))){
                    $.validator.messages.chineseAndLetterExtend = "<i class='fa fa-times-circle'>输入内容不能包含字母或中文</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.chineseAndLetterExtend = "<i class='fa fa-times-circle'>输入内容除了包含字母或中文,还必须包含额外字符</i>";
        return this.optional(element) || !(FormVerifyRegEx.chineseAndLetter.test(value));
    });

    /**
     * 验证字母、数字、中文
     * 传入true表示必须是字母、数字、中文,
     * "false"表示输入内容不能包含字母、数字或中文,
     * "other"表示是除了包含字母、数字或中文,还必须包含额外字符
     */
    $.validator.addMethod("chineseAndLetterAndNumberExtend", function (value, element, params) {
        if (params === true) {
            $.validator.messages.chineseAndLetterAndNumberExtend = "<i class='fa fa-times-circle'>输入内容必须是字母、数字、中文</i>";
            return this.optional(element) || (FormVerifyRegEx.chineseAndLetterAndNumber.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.chineseAndLetterAndNumber.test(value.substr(i,1))){
                    $.validator.messages.chineseAndLetterAndNumberExtend = "<i class='fa fa-times-circle'>输入内容不能包含字母、数字或中文</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.chineseAndLetterAndNumberExtend = "<i class='fa fa-times-circle'>输入内容除了包含字母、数字或中文,还必须包含额外字符</i>";
        return this.optional(element) || !(FormVerifyRegEx.chineseAndLetterAndNumber.test(value));
    });


    /**
     * 验证字母、数字、中文、下划线
     * 传入true表示必须是字母、数字、中文,
     * "false"表示输入内容不能包含字母、数字、中文或下划线,
     * "other"表示是除了包含字母、数字、中文或下划线,还必须包含额外字符
     */
    $.validator.addMethod("chineseAndLetterAndNumberAndUnderExtend", function (value, element, params) {
        if (params === true) {
            $.validator.messages.chineseAndLetterAndNumberAndUnderExtend = "<i class='fa fa-times-circle'>输入内容必须是字母、数字、中文、下划线</i>";
            return this.optional(element) || (FormVerifyRegEx.chineseAndLetterAndNumberAndUnder.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.chineseAndLetterAndNumberAndUnder.test(value.substr(i,1))){
                    $.validator.messages.chineseAndLetterAndNumberAndUnderExtend = "<i class='fa fa-times-circle'>输入内容不能包含字母、数字、中文或下划线</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.chineseAndLetterAndNumberAndUnderExtend = "<i class='fa fa-times-circle'>输入内容除了包含字母、数字、中文或下划线,还必须包含额外字符</i>";
        return this.optional(element) || !(FormVerifyRegEx.chineseAndLetterAndNumberAndUnder.test(value));
    });


    /**
     * 验证字母、数字、中文、下划线、短横线
     * 传入true表示必须是字母、数字、中文、短横线,
     * "false"表示输入内容不能包含字母、数字、中文、下划线或短横线,
     * "other"表示是除了包含字母、数字、中文、下划线或短横线,还必须包含额外字符
     */
    $.validator.addMethod("chineseAndLetterAndNumberAndLineExtend", function (value, element, params) {
        if (params === true) {
            $.validator.messages.chineseAndLetterAndNumberAndLineExtend = "<i class='fa fa-times-circle'>输入内容必须是字母、数字、中文、下划线、短横线</i>";
            return this.optional(element) || (FormVerifyRegEx.chineseAndLetterAndNumberAndLine.test(value));
        }else if(params === "false"){
            var sign = true;
            for(var i=0;i<value.length;i++){
                if(FormVerifyRegEx.chineseAndLetterAndNumberAndLine.test(value.substr(i,1))){
                    $.validator.messages.chineseAndLetterAndNumberAndLineExtend = "<i class='fa fa-times-circle'>输入内容不能包含字母、数字、中文、下划线或短横线</i>";
                    sign = false;
                    break;
                }
            }
            return this.optional(element) || sign;
        }
        $.validator.messages.chineseAndLetterAndNumberAndLineExtend = "<i class='fa fa-times-circle'>输入内容除了包含字母、数字、中文、下划线或短横线,还必须包含额外字符</i>";
        return this.optional(element) || !(FormVerifyRegEx.chineseAndLetterAndNumberAndLine.test(value));
    });

    /**
     * 验证身份证
     * 传入参数为true,即开启验证
     */
    jQuery.validator.addMethod("idNumberExtend", function (value, element) {
        var length = value.length;
        return this.optional(element) || (FormVerifyRegEx.idCard.test(value));
    }, "<i class='fa fa-times-circle'>身份证件号输入格式有误</i>");

    /**
     * 验证邮箱
     * 传入参数为true,即开启验证
     */
    jQuery.validator.addMethod("emilExtend", function (value, element) {
        var length = value.length;
        return this.optional(element) || (FormVerifyRegEx.email.test(value));
    }, "<i class='fa fa-times-circle'>邮箱格式输入错误</i>");

    /**
     * 验证手机号码
     * 传入参数为true,即开启验证
     */
    jQuery.validator.addMethod("telephoneExtend", function (value, element) {
        return this.optional(element) || (FormVerifyRegEx.telephone.test(value))
    }, "<i class='fa fa-times-circle'>请输入正确的11位有效手机号码</i>");

    /**
     * 验证座机号码
     * 传入参数为true,即开启验证
     */
    jQuery.validator.addMethod("planeExtend", function (value, element) {
        return this.optional(element) || (FormVerifyRegEx.plane.test(value))
    }, "<i class='fa fa-times-circle'>请输入正确的8位有效座机号码</i>");

    /**
     * 验证url地址
     * 传入参数为true,即开启验证
     */
    jQuery.validator.addMethod("urlExtend", function (value, element) {
        return this.optional(element) || (FormVerifyRegEx.url.test(value))
    }, "<i class='fa fa-times-circle'>请输入正确的URL地址链接</i>");

    /**
     * 验证时间格式为yy-MM-dd
     * 传入参数为true,即开启验证
     */
    jQuery.validator.addMethod("dateExtend", function (value, element) {
        return this.optional(element) || (FormVerifyRegEx.dateIso.test(value))
    }, "<i class='fa fa-times-circle'>请输入格式为yy-MM-dd</i>");


    /**
     * 后台检测唯一性
     * 传入参数params为数组,第一个参数是传到后台的名字,第二个是url地址,第三个为错误提示信息
     * 格式为:checkUniquenessExtend:["telephone",ctx + "vip/customer/checkPhone","手机号已经存在"]这种
     */
    jQuery.validator.addMethod("checkUniquenessExtend", function (value, element,params) {
        if(isEmptyForString(value)){
            return this.optional(element);
        }
        if(isEmptyForObject(params) || params.length <3){
            return this.optional(element);
        }
        var data = {};
        data[params[0]] = value.trim();
        var isUniqueness = true;
        $.ajax({
            type: "POST",
            url: params[1],
            data: data,
            async: false,
            success: function(result){
                //这个是后台传过来的数据,code=0,表示没有找到相同数据,也就是唯一的,
                //这个需要根据你自己的返回来判定,记住如果后台没有找到数据就说明了唯一性,那么这里isUniqueness就要赋值为true,表示通过验证
                if (result.code === 0){
                    isUniqueness = true;
                }else {
                    isUniqueness = false;
                    $.validator.messages.checkUniquenessExtend = "<i class='fa fa-times-circle'>"+params[2]+"</i>";
                }

            },
            error:function () {
                $.validator.messages.checkUniquenessExtend = "提交数据出错";
            }
        });
        return this.optional(element) || isUniqueness;
    });

    /**
     * 校验输入唯一性,相同name数据,校验是否已经输入
     * 传入格式:第一个传入值为相同name元素的name值,第二个为错误信息提示
     * 例子:inputUniquenessExtend:["telephones","该手机号已经输入过了"]
     */
    jQuery.validator.addMethod("inputUniquenessExtend", function (value,element,params) {
        if(isEmptyForString(value)){
            return this.optional(element);
        }
        if(isEmptyForObject(params) || params.length <2){
            return this.optional(element);
        }
        var isUniqueness = true;
        var obj = $("input[name ='"+params[0]+"']");
        if(!isEmptyForObject(obj) && obj.length >1){
            $("input[name='"+params[0]+"']").each(function(){
                if(value === $(this).val() && element.id != $(this).attr("id")){
                    isUniqueness = false;
                    $.validator.messages.inputUniquenessExtend = "<i class='fa fa-times-circle'>"+params[1]+"</i>";
                    return false;
                }
            });
        }
        return this.optional(element) || isUniqueness;
    });

});


/**
 * 解决jquery表单验证name值相同只验证第一个的问题
 */
$(function () {
    function jqueryVerify() {
        if ($.validator) {
            $.validator.prototype.elements = function () {
                var validator = this,
                    rulesCache = {};
                // Select all valid inputs inside the form (no submit or reset buttons)
                return $(this.currentForm)
                    .find("input, select, textarea, [contenteditable]")
                    .not(":submit, :reset, :image, :disabled")
                    .not(this.settings.ignore)
                    .filter(function () {
                        var name = this.id || this.name || $(this).attr("name"); // For contenteditable
                        if (!name && validator.settings.debug && window.console) {
                            console.error("%o has no name assigned", this);
                        }
                        // Set form expando on contenteditable
                        if (this.hasAttribute("contenteditable")) {
                            this.form = $(this).closest("form")[0];
                        }
                        // Select only the first element for each name, and only those with rules specified
                        if (name in rulesCache || !validator.objectLength($(this).rules())) {
                            return false;
                        }
                        rulesCache[name] = true;
                        return true;
                    });
            }
        }
    }

    jqueryVerify();
});


/*   jQuery.validator()内置方法
* required()	Boolean	必填验证元素。
required(dependency-expression)	Boolean	必填元素依赖于表达式的结果。
required(dependency-callback)	Boolean	必填元素依赖于回调函数的结果。
remote(url)	Boolean	请求远程校验。url 通常是一个远程调用方法。
minlength(length)	Boolean	设置最小长度。
maxlength(length)	Boolean	设置最大长度。
rangelength(range)	Boolean	设置一个长度范围 [min,max]。
min(value)	Boolean	设置最小值。
max(value)	Boolean	设置最大值。
email()	Boolean	验证电子邮箱格式。
range(range)	Boolean	设置值的范围。
url()	Boolean	验证 URL 格式。
date()	Boolean	验证日期格式(类似 30/30/2008 的格式,不验证日期准确性只验证格式)。
dateISO()	Boolean	验证 ISO 类型的日期格式。
dateDE()	Boolean	验证德式的日期格式(29.04.1994 或 1.1.2006)。
number()	Boolean	验证十进制数字(包括小数的)。
digits()	Boolean	验证整数。
creditcard()	Boolean	验证信用卡号。
accept(extension)	Boolean	验证相同后缀名的字符串。
equalTo(other)	Boolean	验证两个输入框的内容是否相同。
phoneUS()	Boolean	验证美式的电话号码。
*
* */

如果要直接使用的话,引入common.js和form-verify.js即可,common.js在上面

下面是一个提示信息及定位的方法:需要借助layer,需要的可以看下

/**
 * 提示信息及定位方法,验证框架这个是没用的,如果你自己写验证,不用这个插件,那么错误提示定位可以用这个,必须引入layer
 * @param msg 显示的提示信息
 * @param idName 要定位的元素id
 * @param time 提示层显示时间
 * @param slideTime 滑动到错误地点时间
 */
function tips(msg, idName, time, slideTime) {
    layer.tips(msg, '#' + idName, {
        tips: [1, '#3595CC'],
        time: time
    });
    $("html,body").animate({scrollTop: $("#" + idName).offset().top}, slideTime);
}

效果:

猜你喜欢

转载自blog.csdn.net/IT_CREATE/article/details/94743555