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)

3 Responses

  1. Dude, I try that code out in .Net and does not work.

  2. I recommend trying it in JavaScript.

  3. Nice one man, thanx a lot

Leave a Reply