名称

返回类型

描述

validate(options)

返回:Validator

验证所选的FORM

valid()

返回:Boolean

检查是否验证通过

rules()

返回:Options

返回元素的验证规则

rules("add",rules)

返回:Options

增加验证规则

rules("remove",rules)

返回:Options

删除验证规则

removeAttrs(attributes)

返回:Options

删除特殊属性并且返回他们

Custom selectors

:blank

返回:Validator

没有值的筛选器

:filled

返回:Array <Element >

有值的筛选器

:unchecked

返回:Array <Element >

没选择的元素的筛选器

Utilities

jQuery.format

(template,argument ,argumentN...)

返回:String

用参数代替模板中的 {n}

 

 

Validator:

validate方法返回一个Validator对象,它有很多方法, 让你能使用引发校验程序或者改变form的内容. validator对象有很多方法,但下面只是列出常用的

form()

返回:Boolean

验证form返回成功还是失败

element(element)

返回:Boolean

验证单个元素是成功还是失败

resetForm()

返回:undefined

把前面验证的FORM恢复到验证前原来的状态

showErrors(errors)

返回:undefined

显示特定的错误信息

Validator functions:

setDefaults(defaults)

返回:undefined

改变默认的设置

addMethod(name,method,message)

返回:undefined

添加一个新的验证方法. 必须包括一个独一无二的名字,一个JAVASCRIPT的方法和一个默认的信息

addClassRules(name,rules)

返回:undefined

增加组合验证类型 在一个类里面用多种验证方法里比较有用

addClassRules(rules)

返回:undefined

增加组合验证类型 在一个类里面用多种验证方法里比较有用,这个是一下子加多个

 

 

内置验证方式:

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 or 1.1.2006)

number()

返回:Boolean

验证十进制数字(包括小数的)

digits()

返回:Boolean

验证整数

creditcard()

返回:Boolean

验证信用卡号

accept(extension)

返回:Boolean

验证相同后缀名的字符串

equalTo(other)

返回:Boolean

验证两个输入框的内容是否相同

phoneUS()

返回:Boolean

验证美式的电话号码

 

 

validate ()的可选项:

debug:进行调试模式(表单不提交):

$(".selector").validate

({

debug:true

})

把调试设置为默认:

$.validator.setDefaults({

debug:true

})

submitHandler:

通过验证后运行的函数,里面要加上表单提交的函数,否则表单不会提交

$(".selector").validate({

submitHandler:function(form) {

$(form).ajaxSubmit();

}

})

ignore:

对某些元素不进行验证

$("#myform").validate({

ignore:".ignore"

})

rules:

自定义规则,key:value的形式,key是要验证的元素,value可以是字符串或对象

$(".selector").validate({

rules:{

name:"required",

email:{

required:true,

email:true

}

}

})

messages:

自定义的提示信息key:value的形式key是要验证的元素,值是字符串或函数

$(".selector").validate({

rules:{

name:"required",

email:{

required:true,

email:true

}

},

messages:{

name:"Name不能为空",

email:{

required:"E-mail不能为空",

email:"E-mail地址不正确"

}

}

})

groups:

对一组元素的验证,用一个错误提示,用error Placement控制把出错信息放在哪里

$("#myform").validate({

groups:{

username:"fname lname"

},

errorPlacement:function(error,element) {

if (element.attr("name") == "fname" || element.attr("name") == "lname")

error.insertAfter("#lastname");

else

error.insertAfter(element);

},

debug:true

})

Onubmit Boolean 默认:true

是否提交时验证

$(".selector").validate({

onsubmit:false

})

onfocusout Boolean 默认:true

是否在获取焦点时验证

$(".selector").validate({

onfocusout:false

})

onkeyup Boolean 默认:true

是否在敲击键盘时验证

$(".selector").validate({

onkeyup:false

})

onclick Boolean 默认:true

是否在鼠标点击时验证(一般验证checkbox,radiobox)

$(".selector").validate({

onclick:false

})

focusInvalid Boolean 默认:true

提交表单后,未通过验证的表单(第一个或提交之前获得焦点的未通过验证的表单)会获得焦点

$(".selector").validate({

focusInvalid:false

})

focusCleanup Boolean 默认:false

当未通过验证的元素获得焦点时,并移除错误提示(避免和 focusInvalid.一起使用)

$(".selector").validate({

focusCleanup:true

})

errorClass String默认:"error"

指定错误提示的css类名,可以自定义错误提示的样式

$(".selector").validate({

errorClass:"invalid"

})

errorElement String 默认:"label"

使用什么标签标记错误

$(".selector").validate

errorElement:"em"

})

wrapper String

使用什么标签再把上边的errorELement包起来

$(".selector").validate({

wrapper:"li"

})

errorLabelContainer Selector

把错误信息统一放在一个容器里面

$("#myform").validate({

errorLabelContainer:"#messageBox",

wrapper:"li",

submitHandler:function() { alert("Submitted!") }

})

showErrors:

跟一个函数,可以显示总共有多少个未通过验证的元素

$(".selector").validate({

showErrors:function(errorMap,errorList) {

$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");

this.defaultShowErrors();

}

})

errorPlacement:

跟一个函数,可以自定义错误放到哪里

$("#myform").validate({

rrorPlacement:function(error,element) {  error.appendTo(element.parent("td").next("td"));

},

debug:true

})

success:

要验证的元素通过验证后的动作,如果跟一个字符串,会当做一个css类,也可跟一个函数

$("#myform").validate({

success:"valid",

submitHandler:function() { alert("Submitted!") }

})

highlight:

可以给未通过验证的元素加效果,闪烁等

 

 

addMethod(name,method,message)方法:

参数name是添加的方法的名字

参数method是一个函数,接收三个参数(value,element,param) value是元素的值,element是元素本身 param是参数,我们可以用addMethod来添加除built-in Validation methods之外的验证方法 比如有一个字段,只能输一个字母,范围是a-f,写法如下:

$.validator.addMethod("af",function(value,element,params){

if(value.length>1){

return false;

}

if(value>=params[0] && value<=params[1]){

return true;

}else{

return false;

}

},"必须是一个字母,且a-f");

用的时候,比如有个表单字段的id="username",则在rules中写

username:{

af:["a","f"]

}

addMethod的第一个参数,就是添加的验证方法的名子,这时是af

addMethod的第三个参数,就是自定义的错误提示,这里的提示为:"必须是一个字母,且a-f"

addMethod的第二个参数,是一个函数,这个比较重要,决定了用这个验证方法时的写法

如果只有一个参数,直接写,如果af:"a",那么a就是这个唯一的参数,如果多个参数,用在[]里,用逗号分开

 

 

meta String方式:

$("#myform").validate({

meta:"validate",

submitHandler:function() { alert("Submitted!") }

})

<script type="text/javascript" src="js/jquery.metadata.js"></script>

<script type="text/javascript" src="js/jquery.validate.js"></script>

<form id="myform">

<input type="text" name="email" class="{validate:{ required:true,email:true }}" />

<input type="submit" value="Submit" />

</form>

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
.error {
color: red;
border-color:red;
} .valid {
color: black;
}
</style>
<script src="js/jquery-3.1.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/validate.js"></script>
</head>
<body>
<div class="contrainer" style="align:center;">
&nbsp;&nbsp; <h2>JQuery Validate 表单验证</h2>
<div class="row " style="margin:100px 20px;">
<div class="col-sm-5 col-sm-offset-2">
<form class="form-horizontal" id="id_frm">
<div class="form-group">
<label for="" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" title="请填写邮箱地址" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" name="password" class="form-control" title="请填写密码" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox">Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$("#id_frm").validate({
rules: {
email: {
required: true,
email: true
},
password: {
required: true, }
},
messages: {
email: {
required: "请填写邮箱地址",
email: "邮箱格式不正确"
},
password: "请填写密码"
},
errorClass: "error",
success: 'valid',
unhighlight: function (element, errorClass, validClass) { //验证通过
$(element).tooltip('destroy').removeClass(errorClass);
},
//highlight: function (element, errorClass, validClass) { //未通过验证
// // TODO
//}
//,
errorPlacement: function (label, element) {
$(element).tooltip('destroy'); /*必需*/
$(element).attr('title', $(label).text()).tooltip('show');
},
submitHandler: function (form) {
alert('验证通过');
}
})
})
</script>
</body>
</html>

bootstrap-tooltip+validate(html代码)

/*! jQuery Validation Plugin - v1.14.0 - 6/30/2015
* http://jqueryvalidation.org/
* Copyright (c) 2015 Jörn Zaefferer; Licensed MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a(jQuery)}(function(a){a.extend(a.fn,{validate:function(b){if(!this.length)return void(b&&b.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.on("click.validate",":submit",function(b){c.settings.submitHandler&&(c.submitButton=b.target),a(this).hasClass("cancel")&&(c.cancelSubmit=!0),void 0!==a(this).attr("formnovalidate")&&(c.cancelSubmit=!0)}),this.on("submit.validate",function(b){function d(){var d,e;return c.settings.submitHandler?(c.submitButton&&(d=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),e=c.settings.submitHandler.call(c,c.currentForm,b),c.submitButton&&d.remove(),void 0!==e?e:!1):!0}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c,d;return a(this[0]).is("form")?b=this.validate().form():(d=[],b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b,d=d.concat(c.errorList)}),c.errorList=d),b},rules:function(b,c){var d,e,f,g,h,i,j=this[0];if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(b,c){i[c]=f[c],delete f[c],"required"===c&&a(j).removeAttr("aria-required")}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g),a(j).attr("aria-required","true")),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}),a.extend(a.expr[":"],{blank:function(b){return!a.trim(""+a(b).val())},filled:function(b){return!!a.trim(""+a(b).val())},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(b,c){var d=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===c.which&&""===this.elementValue(b)||-1!==a.inArray(c.keyCode,d)||(b.name in this.submitted||b===this.lastElement)&&this.element(b)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date ( ISO ).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){var c=a.data(this.form,"validator"),d="on"+b.type.replace(/^validate/,""),e=c.settings;e[d]&&!a(this).is(e.ignore)&&e[d].call(c,this,b)}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){d[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox']",b).on("click.validate","select, option, [type='radio'], [type='checkbox']",b),this.settings.invalidHandler&&a(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler),a(this.currentForm).find("[required], [data-rule-required], .required").attr("aria-required","true")},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c=this.clean(b),d=this.validationTargetFor(c),e=!0;return this.lastElement=d,void 0===d?delete this.invalid[c.name]:(this.prepareElement(d),this.currentElements=a(d),e=this.check(d)!==!1,e?delete this.invalid[d.name]:this.invalid[d.name]=!0),a(b).attr("aria-invalid",!e),this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),e},showErrors:function(b){if(b){a.extend(this.errorMap,b),this.errorList=[];for(var c in b)this.errorList.push({message:b[c],element:this.findByName(c)[0]});this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.submitted={},this.lastElement=null,this.prepareForm(),this.hideErrors();var b,c=this.elements().removeData("previousValue").removeAttr("aria-invalid");if(this.settings.unhighlight)for(b=0;c[b];b++)this.settings.unhighlight.call(this,c[b],this.settings.errorClass,"");else c.removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){return!this.name&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in c||!b.objectLength(a(this).rules())?!1:(c[this.name]=!0,!0)})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([]),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d=a(b),e=b.type;return"radio"===e||"checkbox"===e?this.findByName(b.name).filter(":checked").val():"number"===e&&"undefined"!=typeof b.validity?b.validity.badInput?!1:d.val():(c=d.val(),"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f=a(b).rules(),g=a.map(f,function(a,b){return b}).length,h=!1,i=this.elementValue(b);for(d in f){e={method:d,parameters:f[d]};try{if(c=a.validator.methods[d].call(this,i,b,e.parameters),"dependency-mismatch"===c&&1===g){h=!0;continue}if(h=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(j){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",j),j instanceof TypeError&&(j.message+=". Exception occurred when checking element "+b.id+", check the '"+e.method+"' method."),j}}if(!h)return this.objectLength(f)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(void 0!==arguments[a])return arguments[a];return void 0},defaultMessage:function(b,c){return this.findDefined(this.customMessage(b.name,c),this.customDataMessage(b,c),!this.settings.ignoreTitle&&b.title||void 0,a.validator.messages[c],"<strong>Warning: No message defined for "+b.name+"</strong>")},formatAndAdd:function(b,c){var d=this.defaultMessage(b,c.method),e=/\$?\{(\d+)\}/g;"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),this.errorList.push({message:d,element:b,method:c.method}),this.errorMap[b.name]=d,this.submitted[b.name]=d},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g=this.errorsFor(b),h=this.idOrName(b),i=a(b).attr("aria-describedby");g.length?(g.removeClass(this.settings.validClass).addClass(this.settings.errorClass),g.html(c)):(g=a("<"+this.settings.errorElement+">").attr("id",h+"-error").addClass(this.settings.errorClass).html(c||""),d=g,this.settings.wrapper&&(d=g.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement(d,a(b)):d.insertAfter(b),g.is("label")?g.attr("for",h):0===g.parents("label[for='"+h+"']").length&&(f=g.attr("id").replace(/(:|\.|\[|\]|\$)/g,"\\$1"),i?i.match(new RegExp("\\b"+f+"\\b"))||(i+=" "+f):i=f,a(b).attr("aria-describedby",i),e=this.groups[b.name],e&&a.each(this.groups,function(b,c){c===e&&a("[name='"+b+"']",this.currentForm).attr("aria-describedby",g.attr("id"))}))),!c&&this.settings.success&&(g.text(""),"string"==typeof this.settings.success?g.addClass(this.settings.success):this.settings.success(g,b)),this.toShow=this.toShow.add(g)},errorsFor:function(b){var c=this.idOrName(b),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+d.replace(/\s+/g,", #")),this.errors().filter(e)},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+b+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):!0},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(a){this.pending[a.name]||(this.pendingRequest++,this.pending[a.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],c&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b){return a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,"remote")})},destroy:function(){this.resetForm(),a(this.currentForm).off(".validate").removeData("validator")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},normalizeAttributeRule:function(a,b,c,d){/min|max/.test(c)&&(null===b||/number|range|text/.test(b))&&(d=Number(d),isNaN(d)&&(d=void 0)),d||0===d?a[c]=d:b===c&&"range"!==b&&(a[c]=!0)},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),this.normalizeAttributeRule(e,g,c,d);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),this.normalizeAttributeRule(e,g,c,d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0!==e.param?e.param:!0:delete b[d]}}),a.each(b,function(d,e){b[d]=a.isFunction(e)?e(c):e}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var c;b[this]&&(a.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(c=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(c[0]),Number(c[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:b.length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(?:(?:(?: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.test(a)},date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a).toString())},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9 \-]+/.test(a))return!1;var c,d,e=0,f=0,g=!1;if(a=a.replace(/\D/g,""),a.length<13||a.length>19)return!1;for(c=a.length-1;c>=0;c--)d=a.charAt(c),f=parseInt(d,10),g&&(f*=2)>9&&(f-=9),e+=f,g=!g;return e%10===0},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||d>=e},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||c>=a},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.off(".validate-equalTo").on("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d){if(this.optional(c))return"dependency-mismatch";var e,f,g=this.previousValue(c);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),g.originalMessage=this.settings.messages[c.name].remote,this.settings.messages[c.name].remote=g.message,d="string"==typeof d&&{url:d}||d,g.old===b?g.valid:(g.old=b,e=this,this.startRequest(c),f={},f[c.name]=b,a.ajax(a.extend(!0,{mode:"abort",port:"validate"+c.name,dataType:"json",data:f,context:e.currentForm,success:function(d){var f,h,i,j=d===!0||"true"===d;e.settings.messages[c.name].remote=g.originalMessage,j?(i=e.formSubmitted,e.prepareElement(c),e.formSubmitted=i,e.successList.push(c),delete e.invalid[c.name],e.showErrors()):(f={},h=d||e.defaultMessage(c,"remote"),f[c.name]=g.message=a.isFunction(h)?h(b):h,e.invalid[c.name]=!0,e.showErrors(f)),g.valid=j,e.stopRequest(c,j)}},d)),"pending")}}});var b,c={};a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,d){var e=a.port;"abort"===a.mode&&(c[e]&&c[e].abort(),c[e]=d)}):(b=a.ajax,a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return"abort"===e?(c[f]&&c[f].abort(),c[f]=b.apply(this,arguments),c[f]):b.apply(this,arguments)})});

validate.min.js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
.error {
color: red;
border-color:red;
} .valid {
color: black;
}
</style>
<script src="js/jquery-3.1.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/validate.js"></script>
</head>
<body>
<div class="contrainer" style="align:center;">
&nbsp;&nbsp; <h2>JQuery Validate 表单验证</h2>
<div class="row " style="margin:100px 20px;">
<div class="col-sm-5 col-sm-offset-2">
<form class="form-horizontal" id="id_frm">
<div class="form-group">
<label for="" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" title="请填写邮箱地址" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="text" name="password" class="form-control" title="请填写密码" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox">Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
<input type="submit" value="Submit" />
</div>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$.validator.addMethod("zz",function(value,element,params){
if(""!=value){
var reg = eval(params);
return this .optional(element) || ( reg.test(value));
}
},"格式不正确");
$("#id_frm").validate({
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
zz:"/^[A-Za-z0-9]+$/"
}
},
messages: {
email: {
required: "请填写邮箱地址",
email: "邮箱格式不正确"
},
password: {
required: "请填写密码",
zz:"错了格式"
}
},
errorClass: "error",
success: 'valid',
unhighlight: function (element, errorClass, validClass) { //验证通过
$(element).tooltip('destroy').removeClass(errorClass);
},
//highlight: function (element, errorClass, validClass) { //未通过验证
// // TODO
//}
//,
errorPlacement: function (label, element) {
$(element).tooltip('destroy'); /*必需*/
$(element).attr('title', $(label).text()).tooltip('show');
},
submitHandler: function (form) {
alert('验证通过');
}
})
})
</script>
</body>
</html>

test

可参考

http://blog.csdn.net/qinnimei/article/details/51074797

 

bootstrap-tooltip+validate的更多相关文章

  1. bootstrap插件学习-bootstrap.tooltip.js

    先看bootstrap-tooltip.js的结构 var Tooltip = function ( element, options ){} // 构造器 Tooltip.prototype ={} ...

  2. 扩展Bootstrap Tooltip插件使其可交互

    最近在公司某项目开发中遇见一特殊需求,请笔者帮助,因此有了本文的插件.在前端开发中tooltip是一个极其常用的插件,它能更好向使用者展示更多的文档等帮助信息.它们通常都是一些静态文本信息.但同事他们 ...

  3. bootstrap+jQuery.validate表单校验

    谈谈表单校验 这大概是一种惯例,学习前台后台最开始接触的业务都是用户注册和登录.现在社会坚持以人为本的理念,在网站开发过程同样如此.User是我们面对较多的对象,也是较核心的对象.最开始的用户注册和登 ...

  4. bootstrap+jQuery.validate

    bootstrap+jQuery.validate表单校验   谈谈表单校验 这大概是一种惯例,学习前台后台最开始接触的业务都是用户注册和登录.现在社会坚持以人为本的理念,在网站开发过程同样如此.Us ...

  5. Bootstrap Tooltip

    [Bootstrap Tooltip] 1.设置Tooltip: 1)data-toggle="tooltip" 2)data-placement="top", ...

  6. 基于Bootstrap+jQuery.validate Form表单验证实践

    基于Bootstrap jQuery.validate Form表单验证实践 项目结构 :     github 上源码地址:https://github.com/starzou/front-end- ...

  7. Bootstrap Tooltip源码分析

    /* ======================================================================== * Bootstrap: tooltip.js ...

  8. bootstrap tooltip 显示提示信息

    参照网上文档,是这样说的, <a data-toggle="tooltip" data-placement="top" title="这是要提示 ...

  9. bootstrap Tooltip换行问题

    bootstrap自身带有tooltip,使用起来很方便,但是美中不足,它的tooltip并不支持换行. 比如我们通过<textarea>输入框传入到数据库的长文本,文本是带有换行符的,但 ...

  10. 使用bootstrap tooltip控件动态修改提示内容

    初始化控件之后即使修改了元素的title内容也不会更改提示信息,比如下面 $(element).attr('title','XXXXXX') 这样只会增加一个原生的title提示,如果保持原样显示必须 ...

随机推荐

  1. 深入理解JAVA I/O系列五:对象序列化

    序列化 对象序列化的目标是将对象保存到磁盘中,或者允许在网络中直接传输对象.对象序列化机制允许把内存中的JAVA对象转换成跟平台无关的二进制流,从而允许将这种二进制流持久地保存在磁盘上,通过网络将这种 ...

  2. VS提示“无法启动IIS Express Web服务器”的解决方法

    有时在使用Visual Studio运行项目时,会提示“无法启动IIS Express Web服务器”,如图: 可以依次尝试以下方法(我的情况使用第一种就解决了): 1.可能原因:误操作执行了:Sc ...

  3. 软工网络15团队作业8——Beta阶段冲刺合集

    博客链接集合 Beta阶段敏捷冲刺计划博客 Beta阶段冲刺第一天 Beta阶段冲刺第二天 Beta阶段冲刺第三天 Beta阶段冲刺第四天 Beta阶段冲刺第五天

  4. 前端切图相关ps技术

    标签(空格分隔): 前端切图 复制图层到一个新的ps文件 对于单个图层 1.选中图层 2.CTRL+A全选 3.CTRL+C 4.CTRL+N新建文件,文件大小默认就可以(背景透明也在这个面板设置), ...

  5. android自动化之appium的环境搭建

    简介appium     appium是C/S架构,appium的核心是一个web服务器,它提供了一套REST的接口,他会接收客户端的连接,监听到命令.执行会再将结果通过HTTP响应返还给客户端.ap ...

  6. 第214天:Angular 基础概念

    一.Angular 简介 1. 什么是 AngularJS - 一款非常优秀的前端高级 JS 框架 - 最早由 Misko Hevery 等人创建 - 2009 年被 Google 公式收购,用于其多 ...

  7. Mysql向数据库插入数据时,判断是否存在,若不存在就插入数据

    表中一定要有主键  : select :id,此处的id位置处必须是主键 insert into table_name(id, name, password) select :id, :name, : ...

  8. 【BZOJ4991】我也不知道题目名字是什么(线段树)

    [BZOJ4991]我也不知道题目名字是什么(线段树) 题面 BZOJ 题解 对于线段树维护的区间维护以下东西: 区间左(右)端开始(结束)的最长(短)子串的长度 左端右端的值,以及当前区间内的答案 ...

  9. Android Support WorkManager使用详解

    使用WorkManager调度任务 WorkManager是一个库, 用以将工作入队, 当该工作的约束条件得到满足之后, WorkManager保证它的执行. WorkManager允许观测工作的状态 ...

  10. 【spoj NSUBSTR】 Substrings

    http://www.spoj.com/problems/NSUBSTR/ (题目链接) 题意 给出一个字符串S,令${F(x)}$表示S的所有长度为x的子串出现次数的最大值.求${F(1)..... ...