jQquery.validate自定义规则的使用案例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery.validate自定义规则的使用方法</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript"> //规则名:buga,value检测对像的值
$.validator.addMethod("buga", function(value) {
return value == "buga";
}, 'Please enter "buga"!');
//规则名:chinese,value检测对像的值,element检测的对像
$.validator.addMethod("chinese", function(value, element) {
var chinese = /^[\u4e00-\u9fa5]+$/;
return (chinese.test(value)) || this.optional(element);
}, "只能输入中文");
//规则名:byteRangeLength,value检测对像的值,element检测的对像,param参数
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
var length = value.length;
for (var i = 0; i < value.length; i++) {
if (value.charCodeAt(i) > 127) {
length++;
}
}
return this.optional(element) || (length >= param[0] && length <= param[1]);
}, $.validator.format("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)")); $(function(){ $("#form1").validate({
rules: {
username:{
required:true,
chinese:true,
byteRangeLength:[1,2]
}
//username:"buga"
//username:"chinese"
//username:"byteRangeLength"
}
}); });
</script>
</head> <body> <form id="form1" name="form1" method="post" action="">
<p>
<label for="username">用户名:</label>
<input type="text" name="username" id="username"/>
</p>
<p>
<input type="submit" name="button" id="button" value="提交" />
</p>
</form> </body>
</html>
上一篇:jQuery Validate自定义各种验证方法(转)


下一篇:转 My97日历控件常用功能记录