代码之家  ›  专栏  ›  技术社区  ›  bmatovu Randy the Dev

laravel5.3在自定义验证规则中设置第二个属性名

  •  1
  • bmatovu Randy the Dev  · 技术社区  · 7 年前

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

    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 :other field.

    与我想要的相比;

    The station field is not required with the officer field.

    如何设置错误消息中的第二个参数'officer',方法相同:attribute is。。。??

    1 回复  |  直到 7 年前
        1
  •  1
  •   Robin D'Arcy    7 年前

    您需要添加一个自定义替换程序以符合您的自定义验证规则。请参阅“定义错误消息” here .

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

    这个代码告诉拉威尔 empty_with 如果规则失败,则消息应该在传递回用户之前通过该闭包运行。闭包执行简单的字符串替换并返回修改后的错误消息。

    大多数情况下,每个验证规则都有自己的消息替换规则,因为它依赖于特定属性及其顺序。尽管 :other 对于一些规则来说,第一个参数被替换并不是自动的,而是为每个使用它的规则显式定义的。值得一看 Illuminate\Validation\Concerns\ReplacesAttributes trait来了解Laravel如何处理内置规则的替换。