phpvalidationrespect-validation

Respect Validation: What's the right validation rule when a form has several fields with the same name?


I have a form that has only fields:

Choice is an array because a question has more than answers and the user can add as many as I need.

I just need to validate that these aren't empty so I tried:

$validation = $this->c->validator->validate($request, [
            'question' => v::notEmpty(),
            'choice[]' => v::ArrayVal()->each()->notEmpty()
        ]);

But it doesn't let me save any entry. If I leave choice[] as "choice" it validates every entry. I assume the rule must be wrong.


Solution

  • You can use the KeySet validator:

    $response = v::keySet(
        v::key('question', v::notEmpty()),
        v::key('choice', v::arrayVal())
    )->validate($request);
    

    In the case you use the given value:

    $request = [
        'question' => 'What is your first name?',
        'choice' => []
    ];
    

    the validation returns true.

    In the case you use the given value:

    $request = [
        'question' => 'What is your first name?',
        'choice' => ''
    ];
    

    the validation returns false.