TollerHovler's avatar

How to properly validate a field that is required_if and nullable "if not"

Hello!

Trying to wrap my head around this, solutions I've found does not actually solve my problem.

I need a form field to be a string, with a min and max, IF another field (boolean) is false. If the boolean is true, then the string is effectively optional, and can be null.

In request:

    public function rules() {
        return [
            'condition' => 'required|boolean',
            'string' => 'required_if:condition,false|string|min:3|max:50'
        ];
    }

I see where the problem is, I just don't see what I should do instead. If "condition" is true, then "string" is not 'required' but should still be a string between 3 and 50.

If I send "condition = true" and "string = null (or "")", it fails validation.

So my solution was at first to give it the rule "nullable" to "string"

BUT that would make "string" pass validation EVEN if "condition" is false.

Again, I understand -why- it does, and it makes sense, but after looking through the validation rules and searching around, I notice I don't really know where to go from here.

What I want to achieve is basically:

When "condition" is false, "string" needs to validate as a string between 3 and 50 characters.

When "condition" is true, "string" can be null.

Any hints are much appreciated!

0 likes
1 reply

Please or to participate in this conversation.