Archive for April 19, 2007

JavaScript Number Validation (Repetition)

Posted in JavaScript, Software, Web, internet, programming on April 19, 2007 by Joey

In JavaScript numbers can be validated to be of a certain length. For example, the following regular expression can be used to validate that a numeric value is two digits in length:

document.write(/^\d\d$/.test(22));

This simply calls the \d character class twice. Using curly braces {} this statement can be made even simpler:

document.write(/^\{2}$/.test(22));

The curly braces specify that exactly the number of occurrences specified should be matched. The curly braces can be further expanded to include a comma to specify that the number of digits must match between the length specified in the first and second arguments.

document.write(/^\d{2,4}$/.test(22));

The preceding will match any digit that is between two and four digits in length.

Related articles:
JavaScript Regular Expressions
JavaScript Regular Expression Special Characters: $ ^
JavaScript Number Validation (Integer)
JavaScript Regular Expression Backslash