Search code examples
phpregexformsvalidationpreg-match

Form Validation to Allow 6 or 9 numbers Only?


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?


Solution

  • (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/