Php Laravel 5.1中的自定义验证替换程序
我正在尝试在我的Laravel 5.1应用程序中创建自定义验证替换程序 我现在有Php Laravel 5.1中的自定义验证替换程序,php,validation,laravel-5.1,Php,Validation,Laravel 5.1,我正在尝试在我的Laravel 5.1应用程序中创建自定义验证替换程序 我现在有 Validator::replacer('year', 'App\CustomValidators@replaceYear'); 在我的AppServiceProvider文件中,使用自定义类中相应的living。但是,当我在验证消息中包含:year时,它不会被替换。我错过了什么 这是我的替换函数 public function replaceYear($message, $attribute, $rule, $
Validator::replacer('year', 'App\CustomValidators@replaceYear');
在我的AppServiceProvider
文件中,使用自定义类中相应的living。但是,当我在验证消息中包含:year
时,它不会被替换。我错过了什么
这是我的替换函数
public function replaceYear($message, $attribute, $rule, $parameters)
{
return str_replace([':year'], $parameters, $message);
}
我真正应该做的是将我的替代者设置为类似以下内容:
Validator::replacer('dateInYear', 'App\CustomValidators@replaceDateInYear');
dateInYear
名称与我设置的自定义验证规则的名称相对应。不过,我最终做的是扩展validator类,这样我就不必再声明每个自定义规则和替换规则。我的验证器类现在看起来像这样:
<?php
namespace App\Services;
use Carbon\Carbon;
use \Illuminate\Validation\Validator;
class CustomValidator extends Validator
{
/**
* The new validation rule I want to apply to a field. In this instance,
* I want to check if a submitted date is within a specific year
*/
protected function validateDateInYear($attribute, $value, $parameters, $validator)
{
$date = Carbon::createFromFormat('m/d/Y', $value)->startOfDay();
if ($date->year == $parameters[0]) {
return true;
}
return false;
}
//Custom Replacers
/**
* The replacer that goes with my specific custom validator. They
* should be named the same with a different prefix word so laravel
* knows they should be run together.
*/
protected function replaceDateInYear($message, $attribute, $rule, $parameters)
{
//All custom placeholders that live in the message for
//this rule should live in the first parameter of str_replace
return str_replace([':year'], $parameters, $message);
}
}
这里继承Laravel的验证器的目的是什么?您似乎无法访问任何内部受保护的方法或成员变量,因此这是多余的。除此之外。。。你走上正轨了!向上投票:汉克斯,你的评论帮了我的忙!然而,我犯了一个错误,这在另一个问题中得到了解决。它说你不应该在你的自定义类中扩展验证器,因为这破坏了一切。这个答案让我走上了正确的轨道。我在validation函数中调用了replacer,如下所示:$validator->addReplacer('dateInYear','App\Services\CustomValidator@replaceDateInYear');代码>