Lis*_*isa 3 php validation laravel-5.1
我正在尝试在Laravel 5.1应用程序中创建自定义验证替换器.
我现在有
Validator::replacer('year', 'App\CustomValidators@replaceYear');
Run Code Online (Sandbox Code Playgroud)
在我的AppServiceProvider
文件中,相应的生活在我的自定义类中.但是,当我包含:year
在验证消息中时,它不会被替换.我错过了什么?
这是我的替换功能.
public function replaceYear($message, $attribute, $rule, $parameters)
{
return str_replace([':year'], $parameters, $message);
}
Run Code Online (Sandbox Code Playgroud)
我真正应该做的是设置我的替换器类似于:
Validator::replacer('dateInYear', 'App\CustomValidators@replaceDateInYear');
Run Code Online (Sandbox Code Playgroud)
该dateInYear
名称与我设置的自定义验证规则的名称相对应.然而,我最终做的是扩展验证器类,因此我不再需要声明每个自定义规则和替换器.我的验证器类现在看起来像这样:
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)
这让我可以单独留下我的AppServiceProvider文件,只需要注册新的验证类,我真的可以在任何服务提供商中做.
Laravel的文档特别缺乏替换者需要发生的事情,所以我希望这可以帮助有人在路上.