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

后端 未结 4 1855
失恋的感觉
失恋的感觉 2021-02-19 21:40

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

class ValidatorServiceProvider extends Servic         


        
4条回答
  •  误落风尘
    2021-02-19 22:20

    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.

提交回复
热议问题