Search code examples
phpformsvalidationmodelyii

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?


Solution

  • 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.