Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation no space allowed for username

I have a little problem in laravel validation request. I want to reject username with space like foo bar. I just want to allow foobar without space. Right now my rule is required|unique:user_detail,username. What rule should i use? thanks

like image 504
fzlrhmn Avatar asked Jun 14 '16 03:06

fzlrhmn


Video Answer


3 Answers

Why don't you use alpha_dash rule?

required|alpha_dash|unique:user_detail,username

From the documentation:

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

And it doesn't allow spaces.

like image 69
huuuk Avatar answered Oct 02 '22 04:10

huuuk


You can extend the validator with your own custom rules:

Validator::extend('without_spaces', function($attr, $value){
    return preg_match('/^\S*$/u', $value);
});

Then just use as any other rule:

required|without_spaces|unique:user_detail,username

Checkout the docs on custom validation rules:

https://laravel.com/docs/5.2/validation#custom-validation-rules

like image 36
scrubmx Avatar answered Oct 02 '22 05:10

scrubmx


You should use regular expression with your validation.

PHP :

required|unique:user_detail,username,'regex:/\s/'
like image 4
Aruna Warnasooriya Avatar answered Oct 02 '22 06:10

Aruna Warnasooriya