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:

required|min:6|valid_username|unique:users,username

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()) {


$this->user->AddData($input);


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

}


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

}

I hope you found best solution....


December 19, 2017 | 1975 Viewer | Category : PHP Laravel
Related Posts