Yii2:任何一个字段都需要验证

Saa*_*ani 5 php validation yii active-form

我必须实现标题中提到的验证,即需要两个字段之一(电子邮件,电话).我在我这样做model:

[['email'],'either', ['other' => ['phone']]],
Run Code Online (Sandbox Code Playgroud)

这是方法:

 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;
    }
Run Code Online (Sandbox Code Playgroud)

当我访问我的索引页面时,它给了我这个错误:

异常(未知属性)'yii\base\UnknownPropertyException',消息'设置未知属性:yii\validators\InlineValidator :: 0'

有帮助吗?

Biz*_*ley 6

规则应该是:

['email', 'either', 'params' => ['other' => 'phone']],
Run Code Online (Sandbox Code Playgroud)

方法:

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."));
    }
}
Run Code Online (Sandbox Code Playgroud)


mpl*_*ner 5

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

此解决方案比其他答案短,并且不需要新的验证器类型/类:

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

如果您想获得自定义的错误消息,只需设置以下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); }
  ],
];
Run Code Online (Sandbox Code Playgroud)

  • 如果使用客户端验证,请不要忘记添加“clientWhen”。有关示例,请参阅 /sf/answers/2129293071/。 (2认同)