简体   繁体   English

Yii2:任一字段都需要验证

[英]Yii2: Either one field is required Validation

I have to implement the validation as mentioned in the title that either one of the two fields (email, phone) is required.我必须实现标题中提到的验证,即需要两个字段(电子邮件、电话)之一。 I am doing this in my model :我在我的model这样做:

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

And this is the method:这是方法:

 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;
    }

When I access my index page, it gives me this error:当我访问我的索引页面时,它给了我这个错误:

Exception (Unknown Property) 'yii\\base\\UnknownPropertyException' with message 'Setting unknown property: yii\\validators\\InlineValidator::0'异常(未知属性)“yii\\base\\UnknownPropertyException”,消息为“设置未知属性:yii\\validators\\InlineValidator::0”

Any help?有什么帮助吗?

If you don't care that both fields show an error when the user provides neither of both fields:如果你不关心,当用户提供这两个领域的既不是这两个字段显示一个错误:

This solutions is shorter than the other answers and does not require a new validator type/class:此解决方案比其他答案更短,并且不需要新的验证器类型/类:

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

If you want to have a customized error message, just set the message option:如果您想自定义错误消息,只需设置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); }
  ],
];

The rule should be:规则应该是:

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

And method:和方法:

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

Improved variant改进型

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

Added 'skipOnEmpty'=>false for forcing validating and 'other' can be array添加了'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),
    ]));

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM