Mandatory field, only if another field has a value, must be empty, otherwise

My question is about Laravel validation rules .

I have two inputs aand b. a- this is the entrance to select three possible values: x, yand z. I want to write this rule:

b must have value only if the a value of x. And b must be empty otherwise.

Is there any way to write such a rule? I tried required_with, required_withoutbut it seems that it cannot cover my case.

In other words, if the previous explanation was not clear enough:

  • If a== x, it bshould matter.
  • If the a! = x, bMust be empty.
+4
source share
2 answers

You need to create your own validation rule.

Modify app/Providers/AppServiceProvider.phpand add this validation rule to the method boot:

// Extends the validator
\Validator::extendImplicit(
    'empty_if',
    function ($attribute, $value, $parameters, $validator) {
        $data = request()->input($parameters[0]);
        $parameters_values = array_slice($parameters, 1);
        foreach ($parameters_values as $parameter_value) {
            if ($data == $parameter_value && !empty($value)) {
                return false;
            }
        }
        return true;
    });

// (optional) Display error replacement
\Validator::replacer(
    'empty_if',
    function ($message, $attribute, $rule, $parameters) {
        return str_replace(
            [':other', ':value'], 
            [$parameters[0], request()->input($parameters[0])], 
            $message
        );
    });

(optional) Create an error message in resources/lang/en/validation.php:

'empty_if' => 'The :attribute field must be empty when :other is :value.',

Then use this rule in the controller (s require_if, to observe both rules of the original message):

$attributes = request()->validate([
    'a' => 'required',
    'b' => 'required_if:a,x|empty_if:a,y,z'
]);

It works!

Side note. Perhaps I will create a package for this need with empty_ifand empty_unlessand post a link here

+1
source

Required if

required_if: anotherfield, ,... , .

'b' => 'required_if:a,x'
0

Source: https://habr.com/ru/post/1692628/


All Articles