Search code examples
phpvalidationpreg-matchlaravel-5.1

Laravel 5.1 Creating custom validation rules


In a registration form I the username should only contain a-z A-Z 0-9 underscore, dashes, and dots. So I have defined a custom validator in the boot method of AppServiceProvider as follows;

Validator::extend('valid_username', function ($attribute, $value, $parameters)
            {
                    return preg_match('[a-zA-Z0-9_\-\.]', $value);
            }

But the validation never passes. what I'm doing wrong?


Solution

  • It looks OK, except preg_match requires / at the start and end of the pattern, and you should also match the start/end of the string, as well as tell it to match more than one character:

    Validator::extend('valid_username', function ($attribute, $value, $parameters)
    {
        return preg_match('/^[a-zA-Z0-9_\-\.]+$/', $value);
    }
    

    Your current pattern will only confirm that there is one of those characters, not that there is only those characters.