【问题标题】:Laravel 5.1: custom validation classLaravel 5.1:自定义验证类
【发布时间】:2016-01-23 06:52:34
【问题描述】:

我制作了这个自定义验证类,CustomValidator.php

<?php

namespace App;

use Illuminate\Validation\Validator;

class CustomValidator extends Validator{

    public function validateRequiredWithOneOf($attribute, $value, $parameters)
    {
        $data = $this->getData();
        foreach ($parameters as $p) {
            if ( array_get($data,$p) != null) {return true;}
        }

        return false;
    }

    public function replaceRequiredWithOneOf($message, $attribute, $rule, $parameters)
    {
        return $this->replaceRequiredWith($message, $attribute, $rule, $parameters);
    }
}

我打电话给我的CustomRequest.php

'input_field' => 'required_with_one_of:first,second,third',

如果选择了属性input_field,则还必须选择至少一个参数字段(firstsecondthird)。

如果我在AppServiceProvider.phpboot() 方法中定义自定义验证,则一切正常,但如果我创建此CustomValidator 类并从AppServiceProvider.php 中删除代码,则一切正常。

这并不让我感到惊讶,因为我在 CustomRequest 班级中调用的是 Validator 而不是 CustomValidator

我的CustomRequest 类扩展了Request 类,它扩展了FormRequest 类,其中Validator 在很多地方都被提及。我真的不知道从哪里开始。 如果需要,我可以在此处 c/p FormRequest 课程。

谁能帮我解决这个问题?

【问题讨论】:

    标签: php validation laravel-5.1 custom-validators


    【解决方案1】:

    创建CustomValidator后,只需在boot()方法中调用resolver方法即可:

    \Validator::resolver(function($translator, $data, $rules, $messages)
    {
        return new CustomValidator($translator, $data, $rules, $messages);
    });
    

    另外,在CustomRequest 内部调用它并没有什么不同。应该可以正常工作。

    【讨论】:

    • 谢谢,Validator::... 前面的错字 ` \ ` 还是我遗漏了什么?
    • 不,不是。使用\ 避免命名空间冲突,因为默认情况下php 会认为Validator 是在App 命名空间下声明的类。请记住,Validator 不是一个类,而是一个门面。
    • 我不太明白“避免命名空间冲突”是什么意思,但我会给你“一个”,因为你给了我一些东西给谷歌。
    猜你喜欢
    • 2015-11-24
    • 2016-01-13
    • 1970-01-01
    • 2016-01-13
    • 2015-12-16
    • 2015-10-02
    • 2012-11-27
    • 2015-12-20
    • 2018-08-15
    相关资源
    最近更新 更多