简体   繁体   中英

Laravel Validation - custom rule, custom error message

I'm extending the Laravel Validation rules to create a rule for "between two user-supplied fields" - the between rule only handles "between two values".

Validator::extend('between_fields', function($attribute, $value, $parameters, $validator) {
    $data = $validator->getData();

    $min = array_get( $data, $parameters[0], $parameters[0] );
    $max = array_get( $data, $parameters[1], $parameters[1] );

    return $value >= $min && $value <= $max;
});

This works fine, but I'd then like to define an error message which uses the numeric values. I've set up a message like this:

'between_fields' => ':attribute must be between :min and :max.',

...which is how the existing between rule works, but the :min and :max don't get replaced with anything.

How do I pass the values for those from the Validator extension through to the message handler?

您必须使用Validator::replacer()

Validator::replacer('between_fields', function($message, $attribute, $rule, $parameters){ return str_replace(...); //replace placeholders with the values you want });

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