I have an optional field (say “text1”) which may either be blank or only alpha-numeric:
jQuery.validator.addMethod("onlyAlphaNumeric",
function(value, element) {
var regExp = new RegExp(/^[a-zA-Z0-9]+$/);
return ((this.optional(element)) || regExp.test(value));
}
, "Only aplaha-numeric characters allowed");
$("#student-search-form").validate({
rules : {
text1 : {
optional : true,
onlyAlphaNumeric: "Only a-n allowed"
}
},
messages: {
text : {
acceptOnly: " Only alpha-numeric characters allowed"
}
}
});
The problem is no validation happens, so if user enters “!&^%(*” in ‘text1’, the form gets submitted, no error checks.
Can somebody please tell me what am I doing wrong?
Thank you.
This is wrong…
For
onlyAlphaNumeric:, you can only puttrueorfalse.I am not too sure about
optional:but I knowrequired:is valid… so setrequired:tofalse. Alternatively, you could probably leave it out entirely since the validator defaults to fields as being “optional” (required:false) unless you specify otherwise.See this similar answer…
using the jquery validation plugin, how can I add a regex validation on a textbox?