Reputation: 8310
trying to use regex to validate that a string contains 9 or 12 digits (but not 10 or 11), currently using a list of two regexes and checking the input string twice. Can this be simplified?
var regexes = [/^[0-9]{9}$/, /^[0-9]{12}$/]
for (var i = 0; i < regexes.length; ++i) {
if (regexes[i].test(input))
return true;
}
return false;
Upvotes: 0
Views: 144
Reputation: 4224
var regex = /^[0-9]{9}$|^[0-9]{12}$/;
if (input.match(regex)!= null)
return true;
Upvotes: 2
Reputation: 75598
You could use a regex like this:
/^[0-9]{9}([0-9]{3})?$/
So 9 digits, possibly followed by 3 more digits.
However, there is nothing wrong with checking two possibilities as you have.
Upvotes: 5