Laravel验证自定义消息不起作用

时间:2017-12-03 18:46:54

标签: php laravel laravel-5

我在AppServiceProvider中创建了自定义验证:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('greaterEqual', function($attribute, $value, $parameters, $validator) {
            $min_field = $parameters[0];
            $data = $validator->getData();
            $min_value = $data[$min_field];
            return $value >= $min_value;
        });

        Validator::replacer('greaterEqual', function($message, $attribute, $rule, $parameters) {

            return str_replace(':field', $parameters[0], $message);
        });
    }

    public function register()
    {
        //
    }
}

我想传递自定义验证邮件但没有工作,在提交表单后,我收到此邮件:validation.greater_equal

这是我在控制器中的验证:

$this->validate($request,[
  'quantity' => 'required|min:1|integer|greaterEqual:sale_quantity',
  'sale_quantity' => 'required|min:0|integer',
],[
  'quantity.greaterEqual' => 'The :attribute number is invalid'
]);

我的错误是什么?!

2 个答案:

答案 0 :(得分:0)

我认为你需要resolver ...

 use API\Extensions\Core\CustomLaravelValidator;

    class CustomValidationServiceProvider extends ServiceProvider {

        public function boot()
        {
            $this->app['validator']
                 ->resolver(function($translator, $data, $rules, $messages)
            {
                return new CustomLaravelValidator(
                    $translator, 
                    $data, 
                    $rules, 
                    $messages
                );
            });
        }
    }

答案 1 :(得分:0)

我犯了一个简单的错误。 : - )

1-我添加了sale_quantity翻译:

/resources
    /lang
        /en
            validation.php

2-我编辑了如下代码:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('greater_equal', function($attribute, $value, $parameters, $validator) {
            $min_field = $parameters[0];
            $data = $validator->getData();
            $min_value = $data[$min_field];
            return $value >= $min_value;
        });

        Validator::replacer('greater_equal', function($message, $attribute, $rule, $parameters) {

            return str_replace(':field', trans('validation.attributes.'.$parameters[0]), $message);
        });
    }

    public function register()
    {
        //
    }
}

在控制器中验证:

$this->validate($request,[
  'quantity' => 'required|min:1|integer|greaterqual:sale_quantity',
  'sale_quantity' => 'required|min:0|integer',
],[
  'quantity.greater_equal' => 'The :attribute number is invalid. The value of :attribute must be greater than :field'
]);