Laravel validation no space allowed
Dec 19, 2019
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...
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial