Reputation: 191
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
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 expressioncapture
means to find a match, but store the match for later usewhitespace
can be spaces, tabs or carriage return charactersany amount
can mean zero or moreUpvotes: 0
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