validationlaravel

Laravel validation no space allowed for username


I have a little problem in laravel validation request. I want to reject username with space like foo bar. I just want to allow foobar without space. Right now my rule is required|unique:user_detail,username. What rule should i use? thanks


Solution

  • You can extend the validator with your own custom rules:

    Validator::extend('without_spaces', function($attr, $value){
        return preg_match('/^\S*$/u', $value);
    });
    

    Then just use as any other rule:

    required|without_spaces|unique:user_detail,username
    

    Checkout the docs on custom validation rules:

    https://laravel.com/docs/5.2/validation#custom-validation-rules