Laravel validation username no space allowed alpha_dash or regex custom rule

Panjeh
Panjeh
Feb 28 · 3 min read

If you want to restrict the username in Laravel to only accept letters, numbers, dashes and underscores and not space inside “the username string” you have some options :

Option A:

You should simply put this regex in the validation method like:

'username' => ['required', 'string', 'max:255', 'unique:users', 'regex:/^\S*$/u'],

Note: The above regex is only to avoid space. This is not to avoid other ambiguous characters in the username string.

If you mean exactly accept letters, numbers, dashes and underscores and not space you should follow the Option B.

Option B:

alpha_dash is a default Laravel validation rule which allows letters, numbers, dashes and underscores and NOT space.

When you implement alpha_dash rule, the field under validation may have alpha-numeric characters, as well as dashes and underscores.

'username' => ['required', 'string', 'max:255', 'unique:users', 'alpha_dash'],

Note -1 :

Pay attention that the usual style of validation in Laravel 5.7, 5.8 is a little different with other older versions

Laravel 5.7,5.8:return Validator::make($data, [
'A' => ['required', 'string'],
'B' => ['required', 'string', 'max:255'],
]);

Older versions:
return Validator::make($data, [
'A' => 'required|string',
'B' => 'required|string|max:255',
]);

Note -2 :

If you use alpah_dash and enter some value with some spaces at the end or beginning, it trims and passes the validation and works perfectly.


Thank you for reading! If you enjoyed this article:

Clap it ! Share it! Follow Me in Medium!

Also I’d like to hear your opinion on this article. If you have any doubt, question or suggestion please leave a comment below.

Have a very wonderful day!

Previous Stories You will Love:

Panjeh

Written by

Panjeh

Web geek, Self-taught full-stack web developer, Physicist PhD, Learning Laravel, Vuejs, UX/UI design

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade