laravel - 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
:other
field.
与我想要的相比;
The station field is not required with the officer field.
如何在错误消息中设置第二个参数“officer”,方法相同:attribute is...??
解决方案
您需要添加自定义替换器以符合您的自定义验证规则。请参阅此处的“定义错误消息” 。
\Validator::replacer('empty_with', function ($message, $attribute, $rule, $parameters) {
return str_replace(':other', $parameters[0], $message);
});
这段代码告诉 Laravel,当empty_with
规则失败时,消息应该在返回给用户之前通过该闭包运行。闭包执行简单的字符串替换并返回修改后的错误消息。
在大多数情况下,每个验证规则都有自己的消息替换规则,因为它取决于特定的属性及其顺序。尽管:other
在少数规则中会被第一个参数替换,但它不是自动的,而是为使用它的每个规则明确定义的。值得研究Illuminate\Validation\Concerns\ReplacesAttributes
trait 以了解 Laravel 如何处理其内置规则的替换。
推荐阅读
- python - 无法在 Windows 10 中构建 V8
- r - 如何用第三个变量标记 ggplot2 boxplot 异常值?
- vba - 对在幻灯片中生成图形所需的 VBA 代码进行逆向工程
- matlab - 具有“rand”函数的函数系列(Matlab)
- c# - 在扩展类中获取用户管理器
- android - 发现两个 getter 或属性的区分大小写冲突的字段:c
- python - 出于什么原因使 numpy MGrid 通过复数进行一些索引约定?
- android - 使用 SimpleExoPlayer 和 Room 作为离线缓存
- javascript - 如何让两个 JS Splice 一起工作
- c# - Windows 还原位置有时不起作用