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

时间:2017-01-10 10:25:57

标签: php validation yii active-form

我必须实现标题中提到的验证,即需要两个字段之一(电子邮件,电话)。我在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;
    }

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

  

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

任何帮助?

3 个答案:

答案 0 :(得分:6)

规则应该是:

['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."));
    }
}

答案 1 :(得分:3)

如果您不在乎当用户同时提供两个字段都不显示时,两个字段都显示错误:

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

$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); }
  ],
];

答案 2 :(得分:0)

改进的变体

    settings = Settings(strict = False, xml_huge_tree = True)
    client = Client(wsdl_path, transport = self.transport, wsse = self.wsse,settings = settings)
    client.set_ns_prefix(ns_prefix,namespace)
    service = client.create_service('{{{}}}{}'.format(namespace, binding_name), xaddr)

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

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