简体   繁体   English

带参数的Laravel 5.2自定义验证错误消息

[英]Laravel 5.2 custom validation error message with parameter

I am pretty sure I am missing just something small, but damn-hell can't figure it out.. please help me guys :) 我很确定我只是缺少了一些小东西,但是该死的地狱无法弄清楚..请帮助我:)

I've extended AppServiceProvider.php 我已经扩展了AppServiceProvider.php

public function boot()
    {
        //
        Validator::extend('ageLimit', 'App\Http\CustomValidator@validateAgeLimit');
    }

I've created new CustomValidator.php 我创建了新的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;
        }

    }

}

I've added new line to validation.php 我已经添加了新行到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',
    ],
],  

Here comes my rule: 这是我的规则:

'birth_date' => 'required|date|ageLimit:15', 

All of this works ok ... excluded the parameter :ageLimit in validation.php file .. 所有这些工作正常...排除了validate.php文件中的参数:ageLimit ..

How can I get there the parameter 15 I am passing in rule ??? 如何在规则中传递参数15?

Because I am getting this message: 因为我收到此消息:

Birth day -> Age must be at least :ageLimit years old.

And certainly, I would like to get this: 当然,我想得到这个:

Birth day -> Age must be at least 15 years old.

Below your Validator::extend(...) you could add: 在您的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 https://laravel.com/docs/5.2/validation#custom-validation-rules

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM