Yii2:需要一个字段验证

Yii2: Either one field is required Validation

我必须执行标题中提到的验证,即需要两个字段(电子邮件,phone)之一。我在 model:

中这样做
[['email'],'either', ['other' => ['phone']]],

这是方法:

 public function either($attribute_name, $params) {
        $field1 = $this->getAttributeLabel($attribute_name);
        $field2 = $this->getAttributeLabel($params['other']);
        if (empty($this->$attribute_name) && empty($this->$params['other'])) {
            $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
            return false;
        }
        return true;
    }

当我访问我的索引页面时,出现以下错误:

Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\validators\InlineValidator::0'

有什么帮助吗?

规则应该是:

['email', 'either', 'params' => ['other' => 'phone']],

和方法:

public function either($attribute_name, $params)
{
    $field1 = $this->getAttributeLabel($attribute_name);
    $field2 = $this->getAttributeLabel($params['other']);
    if (empty($this->$attribute_name) && empty($this->{$params['other']})) {
        $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
    }
}

改进的变体

        ['gipsy_team_name', 'either', 'skipOnEmpty'=>false, 'params' => ['other' => 'poker_strategy_nick_name']],
        ['vkontakte', 'either', 'skipOnEmpty'=>false, 'params' => ['other' => ['odnoklasniki','odnoklasniki']]],

添加了'skipOnEmpty'=>false用于强制验证并且'other'可以是数组

/**
 * validation rule
 * @param string $attribute_name
 * @param array $params
 */
public function either($attribute_name, $params)
{
    /**
     * validate actula attribute
     */
    if(!empty($this->$attribute_name)){
        return;
    }

    if(!is_array($params['other'])){
        $params['other'] = [$params['other']];
    }

    /**
     * validate other attributes
     */
    foreach($params['other'] as $field){
        if(!empty($this->$field)){
            return;
        }
    }

    /**
     * get attributes labels
     */
    $fieldsLabels = [$this->getAttributeLabel($attribute_name)];
    foreach($params['other'] as $field){
        $fieldsLabels[] = $this->getAttributeLabel($field);
    }

    $this->addError($attribute_name, \Yii::t('poker_reg', 'One of fields "{fieldList}" is required.',[
        'fieldList' => implode('"", "', $fieldsLabels),
    ]));

}

如果您不关心当用户提供两个字段都不时两个字段都显示错误:

这个解决方案比其他答案更短,不需要新的验证器type/class:

$rules = [
  ['email', 'required', 'when' => function($model) { return empty($model->phone); }],
  ['phone', 'required', 'when' => function($model) { return empty($model->email); }],
];

如果您想要自定义错误消息,只需设置 message 选项:

$rules = [
  [
    'email', 'required',
    'message' => 'Either email or phone is required.',
    'when' => function($model) { return empty($model->phone); }
  ],
  [
    'phone', 'required',
    'message' => 'Either email or phone is required.',
    'when' => function($model) { return empty($model->email); }
  ],
];