I am trying to validate a input field with regex with this pattern [A-Za-z]{,10}
I want it to only find a match if 10 or less chars was sent in the input field, the problem I get is that it will match all words that is less then 10 chars.
Is there a way to say if there is more then 10 chars in the input field come back as false, or is it just better to do a strlen
with php?
If you need to validate that it's alphabetic only, don't use strlen()
. Instead, put boundaries (^$
) on your regex:
/^[A-Za-z]{,10}$/
There is an important syntax mistake being made here by the OP and all the current regex answers: When using the curly brace quantifier with PHP (PCRE), you need to specify the first number. (i.e. The expression: {,10}
is NOT a valid quantifier!) Although the comma and second number are optional, the first number in a curly brace quantifier is required. Thus the expression should be specified like so:
if (preg_match('/^[A-Za-z]{0,10}$/', $text))
// Valid input
else
// Invalid input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With