Patrick
Patrick

Reputation: 8310

Javascript Regex: nine or twelve digits in a string

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

Answers (3)

FailedDev
FailedDev

Reputation: 26930

/^\d{9}(\d{3})?$/

This should work :D

Upvotes: 2

spicavigo
spicavigo

Reputation: 4224

var regex = /^[0-9]{9}$|^[0-9]{12}$/;
if (input.match(regex)!= null)
    return true;

Upvotes: 2

Sjoerd
Sjoerd

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

Related Questions