Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate only alphanumeric, no spaces and only 40 characters

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.

like image 355
GivenPie Avatar asked Dec 26 '22 10:12

GivenPie


2 Answers

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.

like image 93
mathematical.coffee Avatar answered Dec 28 '22 23:12

mathematical.coffee


try [a-zA-Z0-9]{40} this will check 40 characters of alpha numeric with upper and lower case

like image 23
Bikash Shrestha Avatar answered Dec 28 '22 23:12

Bikash Shrestha