0
votes

I am having a hard time understanding this validation rule. Basically, I have two fields, and they are both nullable. But, once both fields are filled, they have to be different from each other. I cannot enter test in both of them, for example. This validation rule works, if I fill both fields.

But, when I only fill one of the fields, the validation fails and says the fields should be different from each other with the following message:

The name and replace must be different.

I checked what is being submitted to my Form Request, and this is the following:

"name" => null
"replace" => "test"

Stripped version of my validation rules:

public function rules()
{
    return [
        'name' => 'different:replace|nullable',
        'replace' => 'different:name|nullable',
    ];
}

Can somebody explain to me what I am misunderstanding with this validation rule? Do null values not count with this rule?

1

1 Answers

4
votes

If you take a look at the validateDifferent function from Illuminate\Validation\Concerns\ValidatesAttributes (vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php:432) rule:

public function validateDifferent($attribute, $value, $parameters)
{
    $this->requireParameterCount(1, $parameters, 'different');

    foreach ($parameters as $parameter) {
        $other = Arr::get($this->data, $parameter);

        if (is_null($other) || $value === $other) {
            return false;
        }
    }

    return true;
}

As you can see in the if case, the rule will fail if the other value is null.

if (is_null($other) || $value === $other)