自定义规则验证不起作用


custom rule validation not working-Yii2

你能帮我一下吗?我确实读了文档,但规则仍然不起作用。我做错了吗?我仍然在寻找一些例子,但仍然没有发生。我想验证用户的密码和repeat_password是否匹配。

这是我在模型中的代码。在这种情况下,这两个也是必需的。

[['password','password_repeat'], 'checkPassword', 'on'=>'create'],

场景也是在actionCreate上声明的。

public function checkPassword($attributes, $params)
    {
        if(!$this->password_repeat === $this->password)
        {
           $this->addError($attribute, 'Passwords do not match!');
        }
    }

我确实尝试在这两个字段上使用compare验证,但它不会满足我。如果只比较一个字段,则不会验证另一个字段。如果您验证了这两个字段,那么当您删除在其中一个字段中输入的内容时,它们仍然有可能相互对照。所以我想创建一个即使你删除了你在那两个字段中输入的内容,谁先去或不去,他们都会被验证。对不起,给您添麻烦了。我希望你还是能得到我想要的结果。谢谢。

PS,我不想使用密码验证器小部件(?)。谢谢你!

您只需在model文件中使用此验证,如…

['password', 'compare', 'compareAttribute'=>'password_repeat',  'message' => 'Your error message'],

在你的代码中

$this->addError($attribute, 'Passwords do not match!');

检查你的varname $属性,它不存在于你的函数声明中。

public function checkPassword($attributes, $params)

AddError不能将错误赋值给表单字段。

试试

<?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?>