Yii2 dependency custom rule validation

守給你的承諾、 提交于 2019-12-08 09:31:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!