Regex to validate alphanumeric, underscores and hyphens with no spaces and only 40 characters
Solution 1
Try
$fnameRegex = "/^[a-zA-Z0-9\-_]{0,40}$/";
Everything in a character class []
will only match one character. You put the quantity limiter outside it (you previously had +
which is 1 or more - replace it with {0, 40} which is between 0 and 40).
Also I escaped your -
character in your character class, or else it will be interpreted as a range.
I also recommend to you the great regexr website which is good for interactively playing around with regex.
Solution 2
try [a-zA-Z0-9]{40} this will check 40 characters of alpha numeric with upper and lower case
GivenPie
Updated on July 05, 2022Comments
-
GivenPie almost 2 years
I wanted to know how I can specify character count for my regex. I have the correct regex, I only need to make sure this will work validating zero to fourty characters.
here is the regex
$fnameRegex = "/^[a-zA-Z0-9{0,40}-_]+$/";
i might have put the
{0,40}
in the wrong place.