Laravel 5 - username custom validation example

Hi Friends,

In this tutorial, i will let you know how to create custom validation for username in laravel 5.5 application. here i will show you controller method and also set custom validation message.

So we may need to add custom validation for username or you have field that no need to add space like without white space, enter value. In this tutorial i will show you simple controller function.

We can simply extend our custom validation like as bellow code:

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

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


Then we can use this way as following example:


As you see, i created "valid_username" customer validation for username column, now i will see you full code for controller method with all code. So let's see bellow code:

Controller Method:

public function store(Request $request)


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

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


$validator = Validator::make($request->all(), [

'name' => 'required',

'username' => 'required|valid_username|min:4|unique:users,username',

'password' => 'required|same:password_confirmation'


['valid_username' => 'please enter valid username.']);

$input = $request->all();

if ($validator->passes()) {


return response()->json(['success'=>'done']);


return response()->json(['error'=>$validator->errors()->all()]);


I hope you found best solution....

December 19, 2017 | 3617 Viewer | Category : PHPLaravel
Related Posts