Laravel 5.4 - How to use multiple error messages for the same custom validation rule

旧街凉风 提交于 2021-02-07 05:19:44

问题


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()
    {
        //
    }
}

And I use this rule like this :

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;
}

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.

Does anyone have an idea ?

=====
EDIT 1 :

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 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 ?


回答1:


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.

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()
    {

    }
}

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
        // ...
    }
}

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.




回答2:


Poor handling of custom validation rules is why I ditched laravel (well, it was one of many reasons, but it was the straw that broke the camel's back, so to speak). But anyway, I have a three part answer for you: a reason why you don't want to do this in this specific case, a quick general overview of the mess you have to deal with, and then the answer to your question in case you still want to do it.

Important security concern

Best security practices for managing logins dictate that you should always return one generic error message for login problems. The quintessential counter-example would be if you returned "That email is not registered with our system" for an email-not-found and "Wrong password" for a correct email with the wrong password. In the case where you give separate validation messages, you give potential attackers additional information about how to more effectively direct their attacks. As a result, all login-related issues should return a generic validation message, regardless of the underlying cause, something to the effect of "Invalid email/password combination". The same is true for password recovery forms, which often say something like, "Password recovery instructions have been sent to that email, if it is present in our system". Otherwise you give attackers (and others) a way to know what email addresses are registered with your system, and that can expose additional attack vectors. So in this particular case, one validation message is what you want.

The trouble with laravel

The issue you are running into is that laravel validators simply return true or false to denote whether or not the rule is met. Error messages are handled separately. You specifically cannot specify the validator error message from inside your validator logic. I know. It's ridiculous, and poorly planned. All you can do is return true or false. You don't have access to anything else to help you, so your pseudo code isn't going to do it.

The (ugly) answer

The simplest way to create your own validation messages is to create your own validator. That looks something like this (inside your controller):

$validator = Validator::make($input, $rules, $messages);

You would still have to create your validator on boot (your Valiator::Extend call. Then you can specify the $rules normally by passing them in to your custom validator. Finally, you can specify your messages. Something like this, overall (inside your controller):

public function login( Request $request )
{
    $rules = [
        'email' => 'bail|required|checkEmailPresenceAndValidity'
    ]

    $messages = [
        'checkEmailPresenceAndValidity' => 'Invalid email.',
    ];

    $validator = Validator::make($request->all(), $rules, $messages);
}

(I don't remember if you have to specify each rule in your $messages array. I don't think so). Of course, even this isn't very awesome, because what you pass for $messages is simply an array of strings (and that is all it is allowed to be). As a result, you still can't have this error message easily change according to user input. This all happens before your validator runs too. Your goal is to have the validation message change depending on the validation results, however laravel forces you to build the messages first. As a result, to really do what you want to do, you have to adjust the actual flow of the system, which isn't very awesome.

A solution would be to have a method in your controller that calculates whether or not your custom validation rule is met. It would do this before you make your validator so that you can send an appropriate message to the validator you build. Then, when you create the validation rule, you can also bind it to the results of your validation calculator, so long as you move your rule definition inside of your controller. You just have to make sure and not accidentally call things out of order. You also have to keep in mind that this requires moving your validation logic outside of the validators, which is fairly hacky. Unfortunately, I'm 95% sure there really isn't any other way to do this.

I've got some example code below. It definitely has some draw backs: your rule is no longer global (it is defined in the controller), the validation logic moves out of the validator (which violates the principle of least astonishment), and you will have to come up with an in-object caching scheme (which isn't hard) to make sure you don't execute your query twice, since the validation logic is called twice. To reiterate, it is definitely hacky, but I'm fairly certain that this is the only way to do what you want to do with laravel. There might be better ways to organize this, but this should at least give you an idea of what you need to make happen.

<?php
namespace App\Http\Controllers;

use User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function __construct() {
        Validator::extend('checkEmailPresenceAndValidity', function ($attribute, $value, $parameters, $validator) {

            return $this->checkLogin( $value ) === true ? true : false;

        });
    }

    public function checkLogin( $email ) {
        $user = User::where('email', $email)->first();

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

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

        return true;
    }

    public function login( Request $request ) {

        $rules = [
            'email' => 'bail|required|checkEmailPresenceAndValidity'
        ]

        $hasError = $this->checkLogin( $request->email );
        if ( $hasError === 'not found' )
            $message = "That email wasn't found";
        elseif ( $hasError === 'invalid' )
            $message = "That is an invalid email";
        else
            $message = "Something was wrong with your request";


        $messages = [
            'checkEmailPresenceAndValidity' => $message,
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            // do something and redirect/exit
        }

        // process successful form here
    }
}

Also, it is worth a quick note that this implementation relies on $this support for closures, which (I believe) was added in PHP 5.4. If you are on an old version of PHP you'll have to provide $this to the closure with use.

Edit to rant

What it really boils down to is that the laravel validation system is designed to be very granular. Each validation rule is specifically only supposed to validate one thing. As a result, the validation message for a given validator should never have to be changed, hence why $messages (when you build your own validator) only accepts plain strings.

In general granularity is a good thing in application design, and something that proper implementation of SOLID principles strive for. However, this particular implementation drives me crazy. My general programming philosophy is that a good implementation should make the most common uses-cases very easy, and then get out of your way for the less-common use-cases. In this cases the architecture of laravel makes the most common use-cases easy but the less common use-cases almost impossible. I'm not okay with that trade off. My general impression of Laravel was that it works great as long as you need to do things the laravel way, but if you have to step out of the box for any reason it is going to actively make your life more difficult. In your case the best answer is to probably just step right back inside that box, i.e. make two validators even if it means making a redundant query. The actual impact on your application performance likely will not matter at all, but the hit you will take to your long-term maintainability to get laravel to behave the way you want it will be quite large.




回答3:


Alternatively to the other proposals, I think you could also call Validator::replacer('yourRule', function()) in addition to Validator::extend('yourRule', function(...)) and keep track of what causes validation failures in the service provider class you're extending the validator from. This way, you are be able to completely replace the default error message with another one.

According to docs, replacer() is meant for making placeholder replacements in the error message before it is being returned, so while this is not strictly that case, it is close enough. Of course, it's kind of an ugly(ish) workaround, but it will probably work (at least it seems to work for me, at a first glance).

One thing to keep in mind though is that you'll probably have to keep track of these failure causes in an array if you want to avoid automatically returning same message for all fields that failed your custom validation rule.




回答4:


Where have you found the error messages for the size validation?

I looked up the validation rules in the Illuminate\Validation\ConcernsValidatesAttributes trait and all functions return a bool value (also the size validation).

protected function validateSize($attribute, $value, $parameters)
{
    $this->requireParameterCount(1, $parameters, 'size');

    return $this->getSize($attribute, $value) == $parameters[0];
}

What you have found belongs to this part:

$keys = ["{$attribute}.{$lowerRule}", $lowerRule];

In this case it's only for formatting the the output by setting a lowerRule value, that laravel handles in special cases, like the size validation:

    // If the rule being validated is a "size" rule, we will need to gather the
    // specific error message for the type of attribute being validated such
    // as a number, file or string which all have different message types.
    elseif (in_array($rule, $this->sizeRules)) {
        return $this->getSizeMessage($attribute, $rule);
    }

So as long as validation rules have to return a bool value there is no way to return more than one error message. Otherwise you have to rewrite some party of the validation rules.

An approach for your problem with the validation you could use the exists validation:

public function rules()
{
    return [
        'email' => ['bail', 'required',  Rule::exists('users')->where(function($query) {
        return $query->where('valid_email', 1);
    })]
    ];
}   

So you would need 2 exists validation rules. I would suggest to use the existing one from laravel to check if the email is set and a custom one to check if the account is validated.



来源:https://stackoverflow.com/questions/44696091/laravel-5-4-how-to-use-multiple-error-messages-for-the-same-custom-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!