Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My question is about Laravel validation rules.

I have two inputs a and b. a is a select input with three possible values: x, y and z. I want to write this rule:

b must have a value only if a values is x. And b must be empty otherwise.

Is there a way to write such a rule? I tried required_with, required_without but it seems it can not cover my case.

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

  • If a == x, b must have a value.
  • If a != x, b must be empty.
like image 403
rap-2-h Avatar asked Jan 24 '18 10:01

rap-2-h


People also ask

How do I use Isblank in validation rule in Salesforce?

ISBLANK(field) returns “True” if the field is blank. ISPICKVAL(field, specific picklist value) returns “True” if a picklist value in a field matches the picklist value in the formula.

What is validation rules in Salesforce?

Validation rules verify that the data a user enters in a record meets the standards you specify before the user can save the record. A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of “True” or “False”.


2 Answers

You have to create your own validation rule.

Edit app/Providers/AppServiceProvider.php and add this validation rule to the boot method:

// 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 a message for error in resources/lang/en/validation.php:

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

Then use this rule in a controller (with require_if to respect both rules of the original post):

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

It works!

Side note: I will maybe create a package for this need with empty_if and empty_unless and post the link here

like image 125
rap-2-h Avatar answered Oct 14 '22 21:10

rap-2-h


Required if

required_if:anotherfield,value,... The field under validation must be present and not empty if the anotherfield field is equal to any value.

'b' => 'required_if:a,x'
like image 45
Levente Otta Avatar answered Oct 14 '22 22:10

Levente Otta