Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tareenmj's avatar

How do I apply custom Validation on an array?

My problem is fairly complex and kind of difficult to explain with text, so I will try my best.

I have three inputs, all as arrays, 'A' 'B' 'C'. I also have a checkbox input 'D' (not an array). Every element in A has to be required if the corresponding element in B or C is non-empty, BUT, if D has a value of 1, A shouldn't be required even if the corresponding elements in B or C are non-empty. If A[1] is empty, and B[1] is empty but C[1] is non-empty, I would like only A[1] to be required, not A[0] or A[2].

I created some rules to try and solve this, but i'm unsure how to solve it.


$validator = Validator::make($output, [
]);

$validator->sometimes('A.*', 'required', function($input){
        if ($input->D==1){//if checkbox D is checked, don't make A required regardless of anything else
            return false;
        }
        if (($input->B!=null) || ($input->C!=null)){//Problem: instead of doing it for the individual elements it will make A required if any element of B or C is non-empty
            return true;
        }
        return false;
    });


0 likes
0 replies

Please or to participate in this conversation.