Yii2:其中一个字段为必填字段

lf3rwulv  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(191)

我必须实现标题中提到的验证,即两个字段(email、phone)中的任意一个是必填字段。

[['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\验证器\内联验证器::0'
有什么帮助吗?

rjee0c15

rjee0c151#

如果您不在乎当用户提供两个字段中的任何一个时两个字段都显示错误:
此解决方案比其他答案更短,并且不需要新的验证器类型/类:

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

zysjyyx42#

规则应该是:

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

edqdpe6u3#

改进的变体

['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),
    ]));

}

相关问题