Yii form model validation- either one is required

Something like this is a bit more generic and can be reused.

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

I was trying to solve same problem today. What I've got is the code below.

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

General idea is to move 'required' validation to custom my_required() method which can check if any of field is filled up.

I see this post is from 2011 however I couldn't find any other solution for it. I Hope it will work for you or other in the future.

Enjoy.


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

in model:

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