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 :
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.
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!
Panjeh — Medium
Read writing from Panjeh on Medium. Physicists PhD, Self-taught web developer #Learning, #laravelphp #Vuejs. Every day…
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!