一、完善的配置
"VALIDATION_OPTION": function(){ return { onfocusout: function(element) { $(element).closest('.form-group').removeClass('has-error'); $(element).valid(); }, onkeyup: function(element) { $(element).closest('.form-group').removeClass('has-error'); $(element).valid(); }, onclick:function(element) { $(element).closest('.form-group').removeClass('has-error'); $(element).valid(); }, errorElement: 'div', errorClass: 'help-block has-error', highlight: function (error,element) { $(error).closest('.form-group').addClass('has-error'); }, errorPlacement: function(error, element) { element.popover({ content:error.outerHTML(), html:true, placement:"bottom", trigger:"focus" }); }, success: function (error,element) { $(element).popover('destroy'); $(error).closest('.form-group').removeClass('has-error');//.addClass('has-info'); }, messages : { "required" : "此项为必填.", "email" : "请输入一个合法的email地址", "url" : "请输入一个合法的url地址.", "date" : "请输入一个合法的日期.", "number" : "请输入一个合法的数字.", "digits" : "请输入一个正整数.", "mobile" : "请输入一个合法的手机号码", "phone" : "请输入一个合法的电话号码", "pwd" : "密码只能是6-16位的数字字母下划线的组合.", "isDate" : "请输入正确的日期(格式为xxxx-xx-xx)", "maxlength": $.validator.format("此项最多只能输入{0}个字符"), "minlength": $.validator.format("此项至少需要输入{0}个字符"), "rangelength": $.validator.format("此项需要输入{0}到{1}个字符"), "range": $.validator.format("Please enter a value between {0} and {1}."), "max": $.validator.format("Please enter a value less than or equal to {0}."), "min": $.validator.format("Please enter a value greater than or equal to {0}.") } }; },
$.validator.addMethod("mobile",function(value,element){ if( !value )return true; return /^(?:13|15|17|18)[0-9]{9}$/.test(value);});$.validator.addMethod("pwd",function(value,element){ var a = /^[a-zA-Z_0-9]{6,16}$/.test(value); return /^[a-zA-Z_0-9]{6,16}$/.test(value);});$.validator.addMethod("phone",function(value,element){ if( !value )return true; return /^(?:[0-9]{3,4}-)?[0-9]{7,8}$/.test(value);});$.validator.addMethod("digits",function(value,element){ if( !value )return true; return this.optional(element) || /^\d+$/.test(value); });$.validator.addMethod("number",function(value,element){ if( !value )return true; return this.optional(element) || /^\d+(\.\d+)?$/.test(value); });$.validator.addMethod("isDate", function(value, element){ if( !value )return true; var ereg = /^(\d{1,4})(-)(\d{1,2})(-)(\d{1,2})$/; var r = value.match(ereg); if (r == null) return false; var d = new Date(r[1], r[3] - 1, r[5]); var result = (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[5]); return this.optional(element) || (result);},"请输入正确的日期(格式为xxxx-xx-xx)");$.validator.messages = $.extend($.validator.messages,Const.VALIDATION_OPTION().messages);
注意:1、后续方法中的 if( !value )return true; 代码可以完成如果输入可以为空,在未输入值或者值被清空时,不会验证
2、 onfocusout、onkeyup、onclick三个参数的配置可以确保输入框值变化的时候进行验证,避免上一次验证的结果残留下来
3、isDate时间格式判断的时候,会与其他的时间插件冲突,导致错误提示不会出现