April 12, 2012
Jquery custom validation non numeric
Question by Brian Perin
I’m trying to write a custom validation function for jquery. The rule should be that the field cannot ONLY be numeric. I know how to write only numeric or only alpha but I want the rule to say that a value of “12345” would fail, but “12345A” would be validated
This is what I have for non numeric
jQuery.validator.addMethod("nonNumeric", function(value, element) {
return this.optional(element) || !value.match(/[0-9]+/);
},"Only alphabatic characters allowed.");
but I can’t figure out how to do not ONLY numeric.
Working script
Here are three rules that might be helpful, the last one is the one that answers this question.
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "No spaces please");
jQuery.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
},"Letters only please.");
jQuery.validator.addMethod("nonNumeric", function(value, element) {
return this.optional(element) || isNaN(Number(value));
},"String cannot be numeric");
Answer by Elliot Bonneville
Use parseInt
(which returns NaN if the operand isn’t strictly a number) like this:
jQuery.validator.addMethod("nonNumeric", function(value, element) {
return this.optional(element) || !isNaN(parseInt(value));
},"Only alphabatic characters allowed.");
Don’t use !=
in this case or you could wind up with this unpleasant situation.
According to Ken Browning‘s comment, parseInt
might not be appropriate here. Try this instead:
jQuery.validator.addMethod("nonNumeric", function(value, element) {
return this.optional(element) || !isNaN(Number(value));
},"Only alphabatic characters allowed.");
Answer by Starx
I think this regex should be enough
/[a-z]/i.test(value);
Usage
jQuery.validator.addMethod("nonNumeric", function(value, element) {
return this.optional(element) || !(/[a-zA-Z]/i.test(value));
},"Only alphabatic characters allowed.");