Laravel 5.4-如何对同一自定义验证规则使用多个错误消息 [英] Laravel 5.4 - How to use multiple error messages for the same custom validation rule

查看:105
本文介绍了Laravel 5.4-如何对同一自定义验证规则使用多个错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了重用代码,我在名为 ValidatorServiceProvider 的文件中创建了自己的验证器规则:

In order to reuse code, I created my own validator rule in a file named ValidatorServiceProvider :

class ValidatorServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('checkEmailPresenceAndValidity', function ($attribute, $value, $parameters, $validator) {
            $user = User::where('email', $value)->first();

            // Email has not been found
            if (! $user) {
                return false;
            }

            // Email has not been validated
            if (! $user->valid_email) {
                return false;
            }

            return true;
        });
    }

    public function register()
    {
        //
    }
}

我使用这样的规则:

public function rules()
{
    return [
        'email' => 'bail|required|checkEmailPresenceAndValidity'
    ];
}

但是,我想为每种情况设置不同的错误消息,如下所示:

But, I want to set different error messages for each case, something like this :

if (! $user) {
    $WHATEVER_INST->error_message = 'email not found';
    return false;
}

if (! $user->valid_email) {
    $WHATEVER_INST->error_message = 'invalid email';
    return false;
}

但我不知道如何在不执行2条差异规则的情况下实现这一目标...
当然,它可以使用多个规则,但也可以执行多个SQL查询,我真的想避免这种情况.
另外,请记住,在实际情况下,我可以在一条规则中进行两次以上的验证.

But I don't figure out how to achieve this without doing 2 differents rules ...
Of course it could work with multiple rules but it will also perform multiple SQL queries, and I really want to avoid that.
Also, keep in mind that in real case I could have more than 2 validations like theses in a single rule.

有人有主意吗?

=====

=====
EDIT 1 :

实际上,我认为我想要的东西的工作方式与 between size 规则类似.
它们代表一个规则,但是提供了多个错误消息:

Actually, I think that I want something that works in a similar way than the beetween or size rules.
They represent one single rule, but provide multiple error messages :

'size'                 => [
    'numeric' => 'The :attribute must be :size.',
    'file'    => 'The :attribute must be :size kilobytes.',
    'string'  => 'The :attribute must be :size characters.',
    'array'   => 'The :attribute must contain :size items.',
],

Laravel检查值是否代表数字,文件,字符串或数组;并获取正确的错误消息以供使用.
我们如何使用自定义规则来实现这种目标?

Laravel checks if the value represents a numeric, a file, a string or an array ; and gets the right error message to use.
How do we achieve this kind of thing with custom rule ?

推荐答案

不幸的是,Laravel当前没有提供直接从属性params数组添加和调用验证规则的具体方法.但这并不排除基于 Trait Request 用法的潜在且友好的解决方案.

Unfortunately Laravel doesn't currently provide a concrete way to add and call your validation rule directly from your attribute params array. But that's does not exclude a potential and friendly solution based on Trait and Request usage.

例如,请在下面找到我的解决方案.

Please find below my solution for example.

第一件事是等待表单被处理以通过抽象类处理我们自己的表单请求.您需要做的是获取当前的 Validator 实例,并在发生任何相关错误时阻止它进行进一步的验证.否则,您将存储验证器实例并调用稍后将创建的自定义用户验证规则函数:

First thing is to wait for the form to be processed to handle the form request ourselve with an abstract class. What you need to do is to get the current Validator instance and prevent it from doing further validations if there's any relevant error. Otherwise, you'll store the validator instance and call your custom user validation rule function that you'll create later :

<?php

namespace App\Custom\Validation;

use \Illuminate\Foundation\Http\FormRequest;

abstract class MyCustomFormRequest extends FormRequest
{
    /** @var \Illuminate\Support\Facades\Validator */
    protected $v = null;

    protected function getValidatorInstance()
    {
        return parent::getValidatorInstance()->after(function ($validator) {
            if ($validator->errors()->all()) {
                // Stop doing further validations
                return;
            }
            $this->v = $validator;
            $this->next();
        });
    }

    /**
     * Add custom post-validation rules
     */
    protected function next()
    {

    }
}

下一步是创建您的 Trait ,这将提供一种方法来验证您的输入,这要归功于当前的验证器实例并处理要显示的正确错误消息:

The next step is to create your Trait which will provide the way to validate your inputs thanks to the current validator instance and handle the correct error message you want to display :

<?php

namespace App\Custom\Validation;

trait CustomUserValidations
{
    protected function validateUserEmailValidity($emailField)
    {
        $email = $this->input($emailField);

        $user = \App\User::where('email', $email)->first();

        if (! $user) {
            return $this->v->errors()->add($emailField, 'Email not found');
        }
        if (! $user->valid_email) {
            return $this->v->errors()->add($emailField, 'Email not valid');
        }

        // MORE VALIDATION POSSIBLE HERE
        // YOU CAN ADD AS MORE AS YOU WANT
        // ...
    }
}

最后,不要忘记扩展您的 MyCustomFormRequest .例如,在您的 php工匠make:request CreateUserRequest 之后,这是简单的方法:

Finally, do not forget to extend your MyCustomFormRequest. For example, after your php artisan make:request CreateUserRequest, here's the easy way to do so :

<?php

namespace App\Http\Requests;

use App\Custom\Validation\MyCustomFormRequest;
use App\Custom\Validation\CustomUserValidations;

class CreateUserRequest extends MyCustomFormRequest
{
    use CustomUserValidations;

    /**
     * Add custom post-validation rules
     */
    public function next()
    {
        $this->validateUserEmailValidity('email');
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'bail|required|email|max:255|unique:users',
            'password' => 'bail|required',
            'name' => 'bail|required|max:255',
            'first_name' => 'bail|required|max:255',
        ];
    }
}

我希望您能按照我的建议找到自己的方式.

I hope that you'll find your way in what I suggest.

这篇关于Laravel 5.4-如何对同一自定义验证规则使用多个错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆