我正在学习jquery验证器插件。我已创建自定义验证器方法并将其应用于名字输入。但它没有工作,并在添加其他验证后也无法正常工作。我只是想知道我做错了什么。
$.validator.setDefaults({
submitHandler: function(){
alert("form submited")
}
})
$('#theform').validate({
rules:{
fname:{
required:true,
name:true
},
lname:"required",
username:{
required:true,
minlength:2
}
},
messages:{
fname:"first name is required",
lname:"last name is required",
username:{
required:"this field is required",
minlength:"atleast two charactor is required"
}
}
})
jQuery.validator.addMethod("name", function(a, b) {
return a.indexOf('john')!=-1;
}, "Please enter name john");
答案 0 :(得分:0)
http://jsfiddle.net/44funjz2/5/
<强> HTML 强>
<form id="theform">
...
<label>name</label>
<input type="namevalidation" id="fname" name="fname" required />
...
</form>
<强> JQ 强>
//to add validator method for name
//1. change input type e.g. "namevalidation"
//2. in addMethod for name take mentioned value: "namevalidation"
//3. addMethod methods must go before attaching validate plugin
$.validator.addMethod("namevalidation", function (a, b) {
return a.indexOf('john') != -1;
}, "Please enter name john");
$('#theform').validate({
//pay attention to the creation of rules and use {} for each rule
rules: {
fname: {
required: true,
},
lname: {
required: true,
},
username: {
required: true,
minlength: 2
}
},
//use {} for each message
messages: {
fname: {
required: "first name is required"
},
lname: {
required: "last name is required"
},
username: {
required: "this field is required",
minlength: "atleast two charactor is required"
}
}
});