In the form, I have three fields: family
, name
and patronymic
.
It is necessary to set up the validation in such a way that if at least one of them was filled, the others also became required. If not one is not completed, then the validation must be successful.
[
['family'],
'required',
'when' => function ($model) {
return $model->name != null and $model->patronymic != null;
},
],
[
['name'],
'required',
'when' => function ($model) {
return $model->family != null and $model->patronymic != null;
},
],
[
['patronymic'],
'required',
'when' => function ($model) {
return $model->family != null and $model->name != null;
},
],
Update
What I suspect is the reason behind you are saying that it isn't working is because you are trying to achieve it on the frontend form or client side whereas you are using
when
in your current set of rules which does not give any idea if you are failing to do it at the frontend form, and it is'nt mentioned anywhere. Although it is working if you initialize the model manually and assign the values on the server side.If that is correct you need to use the
whenClient
along with thewhen
option for the rules.See the updated rules below
You require "if one of the fields is filled, then the rest are required." change the conditions to
OR
instead ofAND
for examplereturn $model->name != null and $model->patronymic != null;
should bereturn $model->name != null OR $model->patronymic != null;
, currently you are checking if both are not null then the field is required , which is inverse of what you want.After changing your rules should look like below