首页 > 解决方案 > Laravel 5.3 在自定义验证规则中设置第二个属性名称

问题描述

我有以下自定义验证规则...

Validator::extend('empty_with', function ($attribute, $value, $parameters, $validator) {
   $other = array_get($validator->getData(), $parameters[0], null);
   return ($value != '' && $other != '') ? false : true;
}, "The :attribute field is not required with the :other field.");

我正在使用它,就像......

$validator = Validator::make($request->all(), [
    'officer' => 'sometimes|integer',
    'station' => 'empty_with:officer,|integer',
]);

当前得到的错误信息是

The station field is not required with the:otherfield.

与我想要的相比;

The station field is not required with the officer field.

如何在错误消息中设置第二个参数“officer”,方法相同:attribute is...??

标签: laravelvalidation

解决方案


您需要添加自定义替换器以符合您的自定义验证规则。请参阅此处的“定义错误消息” 。

\Validator::replacer('empty_with', function ($message, $attribute, $rule, $parameters) {
    return str_replace(':other', $parameters[0], $message);
});

这段代码告诉 Laravel,当empty_with规则失败时,消息应该在返回给用户之前通过该闭包运行。闭包执行简单的字符串替换并返回修改后的错误消息。

在大多数情况下,每个验证规则都有自己的消息替换规则,因为它取决于特定的属性及其顺序。尽管:other在少数规则中会被第一个参数替换,但它不是自动的,而是为使用它的每个规则明确定义的。值得研究Illuminate\Validation\Concerns\ReplacesAttributestrait 以了解 Laravel 如何处理其内置规则的替换。


推荐阅读