简体   繁体   中英

How to show the parameter in message? laravel validator

Note: I done searching a solution from other similar questions but none helped.

I have created a customed validator inside AppServiceProvider.php

Validator::extend('eligible_age', function ($attribute, $value, $parameters, $validator) {
    //some statements here
});

The validator works perfectly like example below

'birthdate' => 'required|eligible_age:22'

My question is how can I show an error message with parameter ? like example below:

The birthdate is not eligible. (must at least 22 years old).

You should use addReplacer to include a named parameter for example age . See example below.

Solution 1 . Directly put the message inside the validator.

Validator::extend('eligible_age', function ($attribute, $value, $parameters, $validator) {

    $validator->addReplacer('eligible_age', function($message, $attribute, $rule, $parameters){
        return str_replace([':age'], $parameters, 'The '. $attribute .' is not eligible. (must at least :age years old).');
    });

    //return either true or false
});

Solution 2 . Just name the parameter, and set the message inside the validation.php.

Validator::extend('eligible_age', function ($attribute, $value, $parameters, $validator) {

    $validator->addReplacer('eligible_age', function($message, $attribute, $rule, $parameters){
        return str_replace([':age'], $parameters, $message);
    });

    //return either true or false
});

And in your message in lang\en\validation.php , you can use age to display the parameter.

'eligible_age' => 'The :attribute is not eligible. (must at least :age years old).'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM