Yii password, repeat password fields

Yii framework repeat/confirm password

Yii framework has awesome input validation mechanism, one of the many validation rules is “compare” rule. You can utilize it for creating confirmation fields to verify user input. Its a good practice to get password input twice while creating signup and change password forms.

class User extends CActiveRecord
{

    public $repeat_password;

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'users';
    }

    public function rules()
    {
        return array(
            array('username', 'required'),
            array('password, repeat_password', 'required', 'on' => 'create'),
            array('password, repeat_password', 'length', 'min' => 6, 'max' => 30, 'on' => array('create', 'update')),
            array('password', 'compare', 'compareAttribute' => 'repeat_password', 'on' => array('create', 'update')),
            array('password, repeat_password', 'length', 'min' => 8),
            array('username', 'length', 'max' => 60),
            array('username', 'unique'),
            array('id, username', 'safe', 'on' => 'search'),
        );
    }

    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
        );
    }

    public function search()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('username', $this->username, true);
        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public function encrypt($parameter)
    {
        return md5($parameter);
    }

    public function beforeSave()
    {
        if (!empty($this->password) && strlen($this->password))
        {
            $this->password = $this->encrypt($this->password);
        } else
        {
            if (empty($this->password))
                $this->password = $this->findByPk($this->id)->password;
        }
        return parent::beforeSave();
    }

}

Author: Tahir Yasin

Tahir is a Passionate Web Developer from Lahore, Pakistan and a guy with NEVER-STOP-LEARNING attitude who keeps an eye on emerging technologies and customer trends.

Leave a Reply

Your email address will not be published. Required fields are marked *