Conditional Validation in Model

I have this model class:

    public function rules()
{
    return [
        [['weekday', 'timetable_entry_subject_id', 'timetable_entry_timetable_group_id', 'start_time', 'end_time'], 'required', 'message'=>'{attribute} Required!'],
        [['timetable_entry_class_timing_id', 'timetable_entry_subject_id', 'timetable_entry_employee_id', 'timetable_entry_academic_year_id', 'timetable_entry_academic_term_id', 'timetable_entry_class_group_id', 'timetable_entry_class_id', 'timetable_entry_class_arm_id', 'is_break', 'is_status', 'created_by', 'updated_by'], 'integer'],
        [['start_time', 'end_time', 'created_at', 'updated_at'], 'safe'],
        [['weekday'], 'string', 'max' => 15],
    ];
}

is_break is tinyint (0 or 1). I want a conditional validation that when is_break is 0, then timetable_entry_subject_id is required. But when is_break is 1, then timetable_entry_subject_id not required.

How do I achieve this?

Thanks

You can use when and whenClient.
https://www.yiiframework.com/doc/guide/2.0/en/input-validation#conditional-validation

return [ 
    [['weekday', 'timetable_entry_timetable_group_id', 'start_time', 'end_time'], 
        'required', 
        'message'=>'{attribute} Required!'
    ],
    [['timetable_entry_subject_id'], 
        'required', 
        'message'=>'{attribute} Required!',
        'when' => function($model) { return $model->is_break == 0; },
        'whenClient' => "function(attribute, value) { return $('#is_break').val() == 0; }",
    ],
   ...
2 Likes

Resolved. Thanks