Form Validation: Field should only be required depending on value of other field

I use the invalid() helper to validate a booking form. A date field should only be required if a radio button for an optional service is checked.

How would I perform such a validation with the invalid() helper, where a field is only required depending on the value of another field? Is this even possible with the invalid() helper?

You could set the required rule for the second field conditionally, depending on whether the radio button is checked or not.

invalid() only checks your conditions against the field values, so if the conditions are right, it can do its job.

Thanks a lot Sonja,

trying to wrap my head around this: With an if statement in the rule definition?

$rules = [
   'firstField'  => ['required'],
   if ??? ...
       'serviceStartDate'  => ['required']
   ???
   'thirdField'  => ['required']
];

Na, not in the middle of the array.

$rules = [
  'firstField'  => ['required'],
  'thirdField'  => ['required'],
];

if ($condition === true) {
   $rules['whateverotherfield'] = ['required'];
}
1 Like

Ah, stupid me! I should definitely improve my basic PHP skills! Thanks a lot!

1 Like