Laravel validation no space allowed

10-Apr-2023

.

Admin

Laravel validation no space allowed

Hi Dev,

Today, I will teach you no space allowed for username in laravel. The username in Laravel to only accept letters, numbers, dashes and underscores not space.

I want to reject username with space like "my username"


. I just want to allow "my_username" without space.

You will enter username without white space is allowed your username or enter username with white space is not allowed.

The username in white space not allowed validation is bellow solution.

Solution 1

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function store(Request $request)

{

$request->validate([

'username' => 'required|regex:/^\S*$/u',

]);

return redirect()->back();

}

Solution 2

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function store(Request $request)

{

\Validator::extend('without_spaces', function($attr, $value){

return preg_match('/^\S*$/u', $value);

});

$request->validate([

'username' => 'required|without_spaces|unique:user_detail,username',

]);

return redirect()->back();

}

It will help you...

#Laravel 7

#Laravel

#Laravel 6