Form Fieldset Validation

Hi everyone!

Quick question to make sure I did not miss anything:
I have a form with one field and one fieldset consisting of two fields.

If one of the fields in the fieldset is filled in by the user, I would like to have them both as required.
If none of them is filled, they should be optional.

Is such a thing possible?

What do mean with “required”? The HTML form element should have the attribute “required” or the input of the input filter should be required?

I would prefer to do it “serverside” through laminas-inputfilter.
If that’s not possible, I will probably need to use javascript and use the required-attribute, right?

Right, nevermind.

I opted for removing empty fieldsets from the interface with a jquery script and left the validators alone.

Why should this not be possible, after all it is normal PHP. :wink:

Here is an example:

class ExampleForm extends Laminas\Form\Form
{
    public function setData($data)
    {
        // Check type of $data here…

        if (array_key_exists('field-one', $data)
            && $data['field-one'] !== ''
        ) {
            $this->getInputFilter()?->get('field-two')->setRequired(true)
                                                      ->setAllowEmpty(false);
        }

        return parent::setData($data);
    }
}
2 Likes

Another option is to define a validation group based on the incoming data.

That’ll work, too, thanks for following up!