问题
I have two input fields consider A and B, now i want to validate that user can input at least one field that is either A or B field.
Is there a way to create a rule condition?
回答1:
Add like this in rules
public function rules()
{
return [
[['field_A'],'required','when' => function($model) {
return $model->field_B == NULL;
}, 'message' => 'Either field_A or field_B is required.'],
[['field_B'],'required','when' => function($model) {
return $model->field_A == NULL;
}, 'message' => 'Either field_A or field_B is required.'],
}
回答2:
You may create individual rule with use closure. Like that:
[['field_a', 'field_b'], function ($attribute, $params) {
// your code
}]
See more in doc
来源:https://stackoverflow.com/questions/29432786/yii2-dependency-custom-rule-validation