JavaScript Number Validation (Repetition)

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

3 Responses to “JavaScript Number Validation (Repetition)”

  1. Interesting…

Leave a Reply