一,jquery.validate这款插件干什么的,有什么用
说简单一点,就是对录入信息进行审核. 好处如下:
1,不要需要在另外去写,email,url,字符,数字等等的审核了
2,插件自带的debug功能,可以让你显示和隐藏,报错信息.
3,里面包含了很多事件,keyup,click,focus,blur等等
4,如果插件满足不了你的验证要求,没问题,你可以用addMethod来添加你的验证方法
5,开发大型网站时,管理信息录入,这个很有必要。插件必尽有专人来研究,肯定会比你想的要全。 我就遇到过这种情况,做电子商务,为商家录入信息,注册就有几个录入,后台添加商品,信息发布,图片,优惠,公告,小文等等,自己写的验证function来控制这些信息录入没问题,但是东西越多,管理起来越不方便。
二,validate的应用实例 http://blog.51yip.com/demo/regist.htm
为了不让页面过长,只贴个JS文件regist.js
function regist(callback){
var aaa = this;
this.init = function(){
aaa.addnotice();
aaa.addm();
aaa.check();
aaa.unchange();
return aaa;
}
this.addnotice = function(){
$("input[type='text']").each(function(){
$(this)
.focus(function(){
if($(this).val() == $(this).attr('notice')){
$(this).val("");
}
})
.blur(function(){
if($(this).val() == $(this).attr('notice') || $.trim($(this).val()) == ""){
$(this).val($(this).attr('notice'));
}
});
});
}
this.cleannotice = function(){
$("input[type='text']").each(function(){
if($(this).val() == $(this).attr('notice')){
$(this).val("");
}
});
}
this.unchange = function(){
$(".select").bind('change',function(){
if($(this).val() == '0'){
$("#citySelect").attr("class","error").html('请选择区域').show();
$("#RegionId").attr("class","error");
}else{
$("#citySelect").attr("class","valid").html('success').show();
$("#RegionId").attr("class","valid");
}
});
}
this.addm = function(){
jQuery.validator.addMethod("iszipcode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");
jQuery.validator.addMethod("engname", function(value, element) {
var tel = /^[a-zA-Z]*$/;
return this.optional(element) || (tel.test(value));
}, "请输入英文字符");
}
this.check = function(){
$('#regist_form').submit(function(){
aaa.cleannotice();
});
$("#regist_form").validate({
rules: {
Name: "required",
engName:{
required:true,
engname:true,
rangelength:[4,10]
},
Email: {
required:true,
email:true,
rangelength:[4,50]
},
postCode: {
required: true,
rangelength:[6,6],
iszipcode: true
},
phone: {
required:true,
number:true,
rangelength:[11,11]
}
},
messages: {
Name: "请输入名字",
engName: {
required: "请输入英文名",
rangelength: jQuery.format("长度请控制在{0} ~ {1}")
},
Email: {
required: "请输入EMAIL",
email: "请输入正确的EMAIL"
},
postCode: {
required: "请输入邮编",
rangelength:jQuery.format("长度必须是6位")
},
phone: {
required: "请输入手机号",
number: "请输入数字",
rangelength: jQuery.format("长度必须是11位")
}
},
success: function(label) {
label.addClass("valid").text("succuess!");
},
submitHandler: function() {
if($("#RegionId").val() == '0'){
$("#citySelect").attr("class","error").html('请选择区域').show();
$("#RegionId").attr("class","error");
}else{
$("#RegionId").attr("class","valid");
$("#citySelect").attr("class","valid").html('success').show();
}
},
debug:true
});
}
}
代码是根oop思想写的
参考文档
http://docs.jquery.com/Plugins/Validation/Methods
转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/jsjquery/792.html