Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii form model validation- either one is required

I have two fields on the form ( forgotpassword form ) username and email Id . User should enter one of them . I mean to retrieve the password user can enter user name or the email id . Could some one point me the validation rule for this ?

Is there any inbuilt rule I can use ?

( Sorry if it is already discussed or if I missed)

Thanks for your help

Regards

Kiran

like image 753
Bujji Avatar asked Aug 16 '11 15:08

Bujji


1 Answers

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()],
    ];
}
like image 97
AndreyTalanin Avatar answered Sep 16 '22 17:09

AndreyTalanin