Laravel validation no space allowed

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
Laravel validation no space allowed

Hi Dev’s, Now Today,I will show you a example of how to no space allowed for username in laravel application. So username in Laravel is only accept letters, numbers, dashes and underscores. It is not accept any space.

So here i want to reject username with space as like as “my username”

So here I just want to allow “my_username” without any space.

Now here we will enter username without any white space is allowed on our username or enter a username also with any white space is not allowed.

So here we see username in white space not allowed in 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();
}

Read Also : How to Implement Chartjs in Laravel?

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →