Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amit123's avatar

regex in validator rules

hello,

Something is wrong with my regex in Laravel a username should only include uppercase letters, lowercase letters and numbers.

public function rules()

{

    return [

        'name' => [

                    'required',

                    'unique:users,name',

                    'min:10',

                    'regex:/[a-z{1}A-Z{1}0-9{1}]+/',

                 ]

    ];

}

According to this site it actually should work: https://regexr.com/

hope you guys could help me again

thanks Amit

0 likes
3 replies
DarkRoast's avatar

Instead of a regex you can use alpha_num.

To solve with a regex it will look something like this: 'regex:/[a-zA-Z0-9]+/', {1} has no limiting effect here it will just be added to the character group.

tykus's avatar

You need to be testing the entire string, also your regexp is needlessly verbose:

'regex:/^[a-zA-Z0-9]+$/',

If you can tolerate underscore (_) in the username, then \w would be neater as a rule

amit123's avatar

alpha_num works. I actually also tried:

'regex:/^[a-zA-Z0-9]+$/',

and many other versions. now I have many invalid entries in my database and i can't delete them because of "safe mode"

Please or to participate in this conversation.