Manu
Manu

Reputation: 191

RegExp to validate the string "900 - 09 999"

What would be the correct Javascript RegExp to validate the following string "900 - 09 999" The string should only allow digits from 0 to 9, an hyphen and a space.

Thanks in advance

Upvotes: 0

Views: 124

Answers (2)

Code Jockey
Code Jockey

Reputation: 6721

If you use this:

inputField.value = inputField.value.replace(/\s*(\d\d\d)\s*-?\s*(\d\d)\s*(\d\d\d)\s*/, "$1 - $2 $3")

...it should both loosely validate AND reformat the value if it does not match perfectly.

broken down, the expression does the following:

\s*          # match any amount of whitespace
(\d\d\d)     # capture three digits
\s*          # match any amount of whitespace
-?           # match an optional hyphen
\s*          # match any amount of whitespace
(\d\d)       # capture two digits
\s*          # match any amount of whitespace
(\d\d\d)     # capture three digits
\s*          # match any amount of whitespace
  • match means to find a set of characters that matches the expression
  • capture means to find a match, but store the match for later use
  • whitespace can be spaces, tabs or carriage return characters
  • any amount can mean zero or more

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

Always be precise when you explain what you want your regex to validate. Are the spaces and hyphens optional or not? This stuff matters. Anyway, this validates the strict format:

"\d{3} \- \d{2} \d{3}"

And this a less strict one:

"\d{3} ?\-? ?\d{2} ?\d{3}"

Upvotes: 1

Related Questions