Yii2 表单验证 - 仅在填写密码字段时比较密码重复 [英] Yii2 form validation - compare password repeat only when password field is filled

查看:32
本文介绍了Yii2 表单验证 - 仅在填写密码字段时比较密码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单验证使用以下规则:

My form validation uses the following rules:

[['password', 'password_repeat'], 'required'],
['password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => "Passwords don't match"],

如何为password_repeat 编写规则以仅在用户填写password 字段时将其与password 进行比较.如果用户跳过passwordpassword_repeat 的验证也应该被跳过.

How to write rules for password_repeat to compare it with password only if user fill password field. If user skip password, validation for password_repeat should be also skipped.

推荐答案

您可以使用 场景:

public function rules() {
    return [
        [['username', 'password'], 'required', 'on' => self::SCENARIO_LOGIN],
        [['username', 'password', 'password_repeat'], 'required', 'on' => self::SCENARIO_REGISTER],
        [
            'password_repeat', 'compare', 'compareAttribute' => 'password',
            'message' => "Passwords don't match", 'on' => self::SCENARIO_REGISTER,
        ],
    ];
}

这允许您为不同的表单设置不同的规则(登录和注册时需要不同的字段).

This allows you to set different rules for different forms (different fields required on login and registration).

您也可以考虑使用自己的 rules() 为不同的表单创建不同的模型,例如 LoginFormRegisterForm.这实际上是更干净的解决方案,并提供更多控制.

You may also consider creating different models for different forms with own rules(), like LoginForm and RegisterForm. This is actually more clean solution and gives more control.

编辑

对于条件规则,你应该使用 when 属性:

For conditional rules you should use when property:

public function rules() {
    return [
        [['password', 'password_repeat'], 'string'],
        [
            'password_repeat', 'compare', 'compareAttribute' => 'password',
            'message' => "Passwords don't match", 'skipOnEmpty' => false,
            'when' => function ($model) {
                return $model->password !== null && $model->password !== '';
            },
        ],
    ];
}

这篇关于Yii2 表单验证 - 仅在填写密码字段时比较密码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆