Reputation: 4345
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.
Upvotes: 1
Views: 1780
Reputation: 98758
This is wrong...
rules : {
text1 : {
optional : true,
onlyAlphaNumeric: "Only a-n allowed"
}
},
For onlyAlphaNumeric:
, you can only put true
or false
.
I am not too sure about optional:
but I know required:
is valid... so set required:
to false
. Alternatively, you could probably leave it out entirely since the validator defaults to fields as being "optional" (required:false
) unless you specify otherwise.
rules : {
text1 : {
required : false,
onlyAlphaNumeric: true
}
},
See this similar answer...
using the jquery validation plugin, how can I add a regex validation on a textbox?
Upvotes: 2
Reputation: 134
I think that your code must be something like this :
// Suppose that your method is well defined
jQuery.validator.addMethod("onlyAlphaNumeric",
function(value, element) {
var regExp = new RegExp(/^[a-zA-Z0-9]+$/);
return ((this.optional(element)) || regExp.test(value));
}
, "Only alpha-numeric characters allowed");
$("#student-search-form").validate({
rules : {
text1 : {
required : false, // optional must be replaced by required
onlyAlphaNumeric: true // rules are boolean
}
},
messages: {
text1 : {
onlyAlphaNumeric: "I can change my message : Only alpha-numeric characters allowed"
}
}
});
Upvotes: 0
Reputation: 52809
you can add optional to the validation method -
http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, spaces or underscores only please");
Validate -
rules : {
text1 : {
alphanumeric: true
}
},
Upvotes: 0