Yii密码重复字段

Mos*_*ted 8 passwords confirmation yii

在创建和更新用户时,我想在基于Yii的Web应用程序中使用密码重复字段.创建时我想要两个字段都需要,当更新时,用户可以将这些字段留空(密码将是相同的)或输入新密码并确认.我怎么能点到它?

Bre*_*son 19

首先,您需要在模型中创建一个新属性(在本例中我们称之为repeatpassword):

class MyModel extends CActiveRecord{
    public $repeatpassword;
    ...
Run Code Online (Sandbox Code Playgroud)

接下来,您需要定义规则以确保它与您现有的密码属性匹配:

    public function rules() {
            return array(
                array('password', 'length', 'max'=>250),
                array('repeatpassword', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match"),
                ...
            );
    }
Run Code Online (Sandbox Code Playgroud)

现在,当创建新模型时,除非密码和repeatpassword属性匹配,否则模型将不会验证.正如您所提到的,这适用于创建新记录,但您不希望在更新时验证匹配的密码.要创建此功能,我们可以使用模型方案

我们只需更改上面所示的repeatpassword规则即可获得额外的parmanter:

...
array('repeatpassword', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match",'on'=>'create'),
...
Run Code Online (Sandbox Code Playgroud)

剩下要做的就是在为create函数声明模型时,使用:

$model = new MyModel('create');
Run Code Online (Sandbox Code Playgroud)

而不是正常:

$model = new MyModel;
Run Code Online (Sandbox Code Playgroud)