在 Laravel 中使用自定义验证规则和替换器时,我真的很难找到任何可以简单地让您获取验证失败的值的文档。
例如,我创建了一个文件存在验证器:
Validator::extend('view_exists', function($field,$value,$parameters)
{
return View::exists($value);
});
Validator::replacer('view_exists', function($message, $attribute, $rule, $parameters)
{
return str_replace(':filename', 'THE ENTERED VALUE', $message);
});
现在,当我创建一个规则是:
$rules = array('filename' => 'required|view_exists');
$messages = array('filename.view_exists' => 'Filename \':filename\' does not exist');
当我输入无效路径时,例如
safsakjhdsafkljh
,我希望它能回来Filename 'safsakjhdsafkljh' does not exist
然而
replacer
无法访问验证失败的值。我已经尝试输出传递给闭包的所有参数,包括 $this
它无处可见:(在我求助于使用之前
Input::get
(呃),我错过了一些完全明显的东西吗?谢谢
加文
最佳答案
使用 Laravel 5.4,您可以在替换回调中访问 Validator 实例,如下所示:
Validator::replacer('view_exists', function ($message, $attribute, $rule, $parameters, Validator $validator) {
$value = array_get($validator->getData(), $attribute);
return str_replace(':filename', $value, $message);
});
关于validation - 在替换器中访问验证失败的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25099624/