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.
Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.
https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs
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!