AleCat83 AleCat83 - 2 months ago 6
PHP Question

Conditional validation, if a checkbox is checked other fields are required

I need to validate a form in the following way:

I have a checkbox and 3 text fields, if the former is checked the latter are required.

Is it possible to achieve this "out of the box"?

Answer

Yes this is possible. I recommend reading the Yii Docs about input validation and especially the part about conditional validation: http://www.yiiframework.com/doc-2.0/guide-input-validation.html#conditional-validation

I guess you'll end up using something like (untested):

[
    ['my_attribute', 'required', 'when' => function($model) {
        return $model->my_checkbox === true;
    }],
]
Comments