Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Pattern Validation

I'm having a bit of trouble getting my pattern to validate the string entry correctly. The PHP portion of this assignment is working correctly, so I won't include that here as to make this easier to read. Can someone tell me why this pattern isn't matching what I'm trying to do?

This pattern has these validation requirements:

  1. Should first have 3-6 lowercase letters
  2. This is immediately followed by either a hyphen or a space
  3. Followed by 1-3 digits

    $codecheck = '/^([[:lower:]]{3,6}-)|([[:lower:]]{3,6} ?)\d{1,3}$/';
    

Currently this catches most of the requirements, but it only seems to validate the minimum character requirements - and doesn't return false when more than 6 or 3 characters (respectively) are entered.

Thanks in advance for any assistance!

like image 753
Shaw Avatar asked Dec 07 '25 08:12

Shaw


1 Answers

The problem here lies in how you group the alternatives. Right now, the regex matches a string that

  • ^([[:lower:]]{3,6}-) - starts with 3-6 lowercase letters followed with a hyphen
  • | - or
  • ([[:lower:]]{3,6} ?)\d{1,3}$ - ends with 3-6 lowercase letters followed with an optional space and followed with 1-3 digits.

In fact, you can get rid of the alternation altogether:

$codecheck = '/^\p{Ll}{3,6}[- ]\d{1,3}$/';

See the regex demo

Explanation:

  • ^ - start of string
  • \p{Ll}{3,6} - 3-6 lowercase letters
  • [- ] - a positive character class matching one character, either a hyphen or a space
  • \d{1,3} - 1-3 digits
  • $ - end of string
like image 79
Wiktor Stribiżew Avatar answered Dec 10 '25 00:12

Wiktor Stribiżew