我很确定我错过了一些小事,但该死的地狱无法弄明白......请帮助我们:)
我已扩展 AppServiceProvider.php
public function boot()
{
//
Validator::extend('ageLimit', 'App\Http\CustomValidator@validateAgeLimit');
}
我创建了新的 CustomValidator.php
<?php
namespace App\Http;
use DateTime;
class CustomValidator {
public function validateAgeLimit($attribute, $value, $parameters, $validator)
{
$today = new DateTime(date('m/d/Y'));
$bday = new DateTime($value);
$diff = $bday->diff($today);
$first_param = $parameters[0];
if( $diff->y >= $first_param ){
return true;
}else{
return false;
}
}
}
我已在 validation.php
添加了新行/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'age_limit' => ':attribute -> Age must be at least :ageLimit years old.',
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
我的规则来了:
'birth_date' => 'required|date|ageLimit:15',
所有这一切都正常......在validation.php文件中排除了参数:ageLimit ..
我如何到达那里我在规则中传递的参数15 ???
因为我收到了这条消息:
Birth day -> Age must be at least :ageLimit years old.
当然,我想得到这个:
Birth day -> Age must be at least 15 years old.
答案 0 :(得分:1)
在Validator::extend(...)
下方,您可以添加:
Validator::replacer('ageLimit', function($message, $attribute, $rule, $parameters) {
$ageLimit = $parameters[0];
return str_replace(':ageLimit', $ageLimit, $message);
});
https://laravel.com/docs/5.2/validation#custom-validation-rules
希望这有帮助!