Yii表单模型验证 - 任何一个都是必需的

Buj*_*jji 11 forms validation model yii

我在表单上有两个字段(forgotpassword表单)用户名和电子邮件ID.用户应输入其中一个.我的意思是检索密码用户可以输入用户名或电子邮件ID.有人可以指出我的验证规则吗?

我可以使用任何内置规则吗?

(对不起,如果已经讨论过或者我错过了)

谢谢你的帮助

问候

基兰

小智 21

我今天试图解决同样的问题.我得到的是下面的代码.

public function rules()
{
    return array(
        // array('username, email', 'required'), // Remove these fields from required!!
        array('email', 'email'),
        array('username, email', 'my_equired'), // do it below any validation of username and email field
    );
}

public function my_required($attribute_name, $params)
{
    if (empty($this->username)
            && empty($this->email)
    ) {
        $this->addError($attribute_name, Yii::t('user', 'At least 1 of the field must be filled up properly'));

        return false;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

一般的想法是将"必需"验证移动到自定义my_required()方法,该方法可以检查是否填充了任何字段.

我看到这篇文章来自2011年,但我找不到任何其他解决方案.我希望它将来会对你或其他人有用.

请享用.


Dam*_*nis 16

这样的东西更通用,可以重复使用.

public function rules() {
    return array(
        array('username','either','other'=>'email'),
    );
}
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)

  • 这应该是公认的答案,因为它更详细并利用了规则参数,因此您不必对验证器函数中的第二个属性进行硬编码. (3认同)

小智 6

Yii2

namespace common\components;

use yii\validators\Validator;

class EitherValidator extends Validator
{
    /**
     * @inheritdoc
     */
    public function validateAttributes($model, $attributes = null)
    {
        $labels = [];
        $values = [];
        $attributes = $this->attributes;
        foreach($attributes as $attribute) {
            $labels[] = $model->getAttributeLabel($attribute);
            if(!empty($model->$attribute)) {
                $values[] = $model->$attribute;
            }
        }

        if (empty($values)) {
            $labels = '«' . implode('» or «', $labels) . '»';
            foreach($attributes as $attribute) {
                $this->addError($model, $attribute, "Fill {$labels}.");
            }
            return false;
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

在模型中:

public function rules()
{
    return [
        [['attribute1', 'attribute2', 'attribute3', ...], EitherValidator::className()],
    ];
}
Run Code Online (Sandbox Code Playgroud)