Reputation: 122
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:
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!
Upvotes: 3
Views: 502
Reputation: 351278
You need to delimit the scope of the |
operator in the middle of your regex.
As it is now:
the right-side argument of that OR runs up until the very end of your regex, even including the $
. So the digits, nor the end-of-string condition do not apply for the left side of the |
.
the left-side argument of the OR starts with ^
, and only applies to the left side.
That is why you get a match when you supply 7 lowercase characters. The first character is ignored, and the rest matches with the right-side of the regex pattern.
Upvotes: 2
Reputation: 627469
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 stringUpvotes: 4