Search code examples
laravelvalidationlaravel-5laravel-validation

Is there a way to attach a custom validation message when extending the validator in laravel?


Currently I have implemented following custom validation, but I don't know how to attach a custom message if the validation fails. To clarify, I need to define the error message when extending validator

Validator::extend('phone_number', function($attribute, $value, $parameters)
    {
       // is there anyway I could define a error message here, if this validation fails,
        if (strlen($value) === 9)
        {
            if (substr($value, 0, 1) === '0')
            {
                return false;
            }
        }
        else
        {
            if (substr($value, 0, 1) != '0')
            {
                return false;
            }
        }

        return true;
    });

I have currently placed this code within boot method, and in documentation they say there's a way to define custom message as follows, but I really don't understand it.

public function boot()
{

Validator::extend(...);

Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
    return str_replace(...);
});

}


Solution

  • You can specify your message by adding a third parameter to the extend method like this :

    Validator::extend('phone_number', function($attribute, $value, $parameters) {
    
        if (strlen($value) === 9)
        {
            if (substr($value, 0, 1) === '0')
            {
                return false;
            }
        }
        else
        {
            if (substr($value, 0, 1) != '0')
            {
                return false;
            }
        }
    
        return true;
    }, 'Your custom message goes here'); // <--- HERE