Reputation: 154
I have a form with a field that accepts numbers only for an access code. Access codes are either 6 or 9 numbers. Currently I'm validating the field with
elseif (( ! is_numeric($values['access'])) || ! preg_match('/[0-9]{6,9}$/', $values['access']))
which allows between 6 and 9 numbers. How can I allow only 6 or 9 numbers?
I'm guess it's something like
elseif (( ! is_numeric($values['access'])) || ! preg_match('/[0-9]{6}[0-9]{9}$/', $values['access']))
But we all know that wont work. Can someone point me in the right direction?
Upvotes: 0
Views: 574
Reputation: 91488
More efficient way, it takes 27 steps (accepted answer 36 steps):
^\d{6}(?:\d{3})?$
Upvotes: 1
Reputation: 12375
(a|b)
will match either a or b. So!
^(\d{6}|\d{9})$
Will match either 6 numerals, or 9 numerals.
Which you can put to the test here https://regex101.com/r/Chx10H/1/
Upvotes: 2