JavaScript to Validate Positive Integer While Accepting Empty String
A few times at work recently we have had the need to validate a form input field as an integer while still accepting an empty sting as a valid value as well.
This can be done as follows:
var RE = /^\d*$/;
document.write(RE.test(2)); //true
document.write(RE.test('')); //true
document.write(RE.test('a')); //false
The regular expression in the preceding example specifies that the string being tested must have zero or more digit characters. Anything else is invalid.
Related articles:
JavaScript Regular Expressions
JavaScript Regular Expression Asterisk
JavaScript Regular Expression Special Characters: ^ $
JavaScript Number Validation (Integer)
July 19, 2007 at 9:01 pm
Dude, I try that code out in .Net and does not work.
July 20, 2007 at 6:08 am
I recommend trying it in JavaScript.
September 4, 2008 at 4:39 am
Nice one man, thanx a lot