jquery validate 用法
$(function() {
//解决validate 多个相同name的问题
if ($.validator) {
//fix: when several input elements shares the same name, but has different id-ies....
$.validator.prototype.elements = function () {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
// workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
return $([]).add(this.currentForm.elements)
.filter(":input")
.not(":submit, :reset, :image, [disabled]")
.not(this.settings.ignore)
.filter(function () {
var elementIdentification = this.id || this.name;
!elementIdentification && validator.settings.debug && window.console && console.error("%o has no id nor name assigned", this);
// select only the first element for each name, and only those with rules specified
if (elementIdentification in rulesCache || !validator.objectLength($(this).rules()))
return false;
rulesCache[elementIdentification] = true;
return true;
});
};
}
addValidate();
});
function addValidate() {
$('#foodRecordForm').validate({
// 校验字段
rules : {
foodContent : {
required : [ "食物用量" ],
number : [ "食物用量" ]
},
foodRecordName : {
required : [ "食物名称" ]
}
},
highlight : function(element, errorClass, validClass) { // element出错时触发
if (!$(element).hasClass(errorClass))
$(element).addClass(errorClass);
},
unhighlight : function(element, errorClass) { // element通过验证时触发
if ($(element).hasClass(errorClass))
$(element).removeClass(errorClass);
},
errorPlacement : function(error, element) {
var obj = getValidateErrorObj($(element));
element.val($(error).text()).focus(function(){
$(this).val("")}); //错误消息提示在文本框内
// obj.find("[data-error]").append(error);//提示在文本框后面
}
});
}
//提交时校验
if (!$(‘#foodRecordForm’).valid()) {
return false;
}
常用校验规则:
1 required:true 必须输入的字段。
2 remote:”check.php” 使用 ajax 方法调用 check.php 验证输入值。
3 email:true 必须输入正确格式的电子邮件。
4 url:true 必须输入正确格式的网址。
5 date:true 必须输入正确格式的日期。日期校验 ie6 出错,慎用。
6 dateISO:true 必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22。只验证格式,不验证有效性。
7 number:true 必须输入合法的数字(负数,小数)。
8 digits:true 必须输入整数。
9 creditcard: 必须输入合法的信用卡号。
10 equalTo:”#field” 输入值必须和 #field 相同。
11 accept: 输入拥有合法后缀名的字符串(上传文件的后缀)。
12 maxlength:5 输入长度最多是 5 的字符串(汉字算一个字符)。
13 minlength:10 输入长度最小是 10 的字符串(汉字算一个字符)。
14 rangelength:[5,10] 输入长度必须介于 5 和 10 之间的字符串(汉字算一个字符)。
15 range:[5,10] 输入值必须介于 5 和 10 之间。
16 max:5 输入值不能大于 5。
17 min:10 输入值不能小于 10。
本文介绍 jQuery Validate 插件的使用方法,包括解决多个相同 name 的元素验证问题,自定义验证规则及错误提示,以及如何进行表单提交前的验证。支持多种常见验证规则,如必填项、邮箱格式等。


被折叠的 条评论
为什么被折叠?



