How to use addmethod in jquery.validate. Example
$("#formname").validate({
rules: {
textbox: {
required: true,
regexp: /['"]/
},
methods: {
required: "Should not be blank",
regexp: "Single quo开发者_如何学JAVAtes and double quotes not allowed"
}
}
});
I need to check this quotes in textbox with addmethod. How can i do this. Explain me by implementing your answer with my sample code.
First we need a few fixes, the layout for messages
is like this (you can't do this with your original options...the plugin just doesn't look for that structure):
$("#formname").validate({
rules: {
textbox: {
required: true,
regexp: /['"]/
}
},
messages: {
textbox: {
required: "Should not be blank",
regexp: "Single quotes and double quotes not allowed"
}
}
});
Then your method would look like this:
$.validator.addMethod("regexp", function(value, element, param) {
return this.optional(element) || !param.test(value);
});
You can test it out here....but you notice your regex is backwards, so the naming's not quite right...I'd rename regexp
to nomatch
...or something more indicative of the behavior you're looking for.
$("#formname").validate({
rules: {
textbox: {
required: true,
regexp: true
}
},
messages: {
textbox: {
required: "Should not be blank",
regexp: "Single quotes and double quotes not allowed"
}
}
});
// Regexp validation
$.validator.addMethod("regexp", function(value, element, arg){
var reg_val=$('#textbox').val();
var regExp=/^['"]+$/;
if($('#textbox').val().match(reg_val)){
return true;
}else{
return false;
}
}, "");
精彩评论