是否可以在替换器中访问未通过验证的值? [英] Get access to value that failed validation, in a replacer?

查看:62
本文介绍了是否可以在替换器中访问未通过验证的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel中使用自定义验证规则和替换器时,我真的很难找到任何可以让您获得验证失败的值的文档.

When using a custom validation rule and replacer within Laravel, I am really struggling to find any documentation that would simply allow you to get the value that failed validation.

例如,我创建了一个文件存在验证器:

For example, I have created a file exists validator:

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);
});

现在,当我创建一个规则时:

Now, when I create a rule that is:

$rules = array('filename' => 'required|view_exists');
$messages = array('filename.view_exists' => 'Filename \':filename\' does not exist');

当我输入无效的路径(例如safsakjhdsafkljh)时,我希望它可以返回

When I enter an invalid path, such as safsakjhdsafkljh, I was hoping it could return

Filename 'safsakjhdsafkljh' does not exist

但是replacer无法访问验证失败的值.我尝试输出所有传递给闭包的参数,包括$this,在哪里都看不到:(

However the replacer is not able to access the value that failed the validation. I've tried outputting all parameters that are passed to the closure, including $this and it's no where to be seen :(

在我使用Input::get(urgh)之前,我是否遗漏了一些显而易见的东西?

Before I resort to using Input::get (urgh), am I missing something completely obvious?

谢谢

Gavin

推荐答案

使用Laravel 5.4,您可以像下面这样在replacer回调中访问Validator实例:

With Laravel 5.4 you can access Validator instance in replacer callback like following:

Validator::replacer('view_exists', function ($message, $attribute, $rule, $parameters, Validator $validator) {
    $value = array_get($validator->getData(), $attribute);

    return str_replace(':filename', $value, $message);
});

这篇关于是否可以在替换器中访问未通过验证的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆