【问题标题】:Combine validation errors and return one single message合并验证错误并返回一条消息
【发布时间】:2018-04-16 01:35:48
【问题描述】:

我想在我的自定义 Request 中验证两个数组:

$rules = [
  'params.words1.*.value' => 'required|string|between:5,50',
  'params.words2.*.value' => 'required|string|between:5,50',
];

这会为每个单词返回一条错误消息。但我想要一条一般性消息,例如“某些词无效”。 有任何 Laravel 方式可以做到这一点吗?

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    你可以这样做:

    $messages = [
        'params.*' => 'Some of the words are invalid.',
    ];
    

    编辑:

    我想我可能已经找到了解决办法:

    首先,确保在顶部同时导入 Validator 和 HttpResponseException:

    use Illuminate\Contracts\Validation\Validator;
    use Illuminate\Http\Exceptions\HttpResponseException;
    

    然后,您可以覆盖本机 failedValidation 方法并根据需要更改错误:

    protected function failedValidation(Validator $validator)
    {
        // Get all the errors thrown
        $errors = collect($validator->errors());
        // Manipulate however you want. I'm just getting the first one here,
        // but you can use whatever logic fits your needs.
        $error  = $errors->unique()->first();
    
        // Either throw the exception, or return it any other way.
        throw new HttpResponseException(response(
            $error,
            422
        ));
    }
    

    【讨论】:

    • 我试过了,但这只会多次发送相同的邮件。 (我将此添加到我的Requestpublic function messages() { $messages = [ 'params.words2.*' => 'Some of the words are invalid.', ]; return $messages; }
    • 查看我的编辑。我想我可能已经找到了解决办法。
    【解决方案2】:

    你试过bail参数吗?

    https://laravel.com/docs/5.6/validation

    这应该只返回第一个验证错误,如果你的所有规则都有相同的验证错误消息,这将得到想要的结果。

    编辑:这适用于 Laravel 5.2 及更高版本。

    【讨论】:

    • 不幸的是,这似乎不适用于数组验证。它仍然验证每个项目并为每个项目返回一条消息。
    • @red1575 你的 laravel 版本是什么?似乎从 5.2 及更高版本开始支持此功能。如果你有一个比那个更新的版本,那么它应该可以工作。如果它仍然无法正常工作,或者您的版本较旧,也许可以尝试使用多个验证器?首先验证 params.words1.*.value 然后另一个验证器来验证 params.words2.*.value - 这只是我的理论,但应该有效。不过绝对不是最漂亮的解决方案。
    • 此外,如果输入中有多个匹配params.words1.*.value 的字段,即使使用bail 参数,它也可能会返回多条消息。如果是这种情况,您可能需要设置更明确的字段名称。
    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 2011-10-22
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2015-11-10
    相关资源
    最近更新 更多