gpt4 book ai didi

php - 比较规则 yii2 无法正常工作

转载 作者:行者123 更新时间:2023-12-02 14:24:31 24 4
gpt4 key购买 nike

我的规则方法如下:

public function rules()
{
return [
[['username', 'email', 'password'],'filter', 'filter' => 'trim'],
[['username', 'email', 'password'],'required', 'message' => '{attribute} can not be empty'],
['username', 'string', 'min' => 2, 'max' => 255],
['password', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'required', 'message' => 'This field can not be empty'],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match", 'skipOnError' => true],
['username', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
['email', 'email'],
['email', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
];
}

我的 View 代码是这样的:

<?php $form = ActiveForm::begin(['action' => 'login/register']); ?>
<?= $form->field($registration, 'username',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_username', 'class' => 'md-input']) ?>

<?= $form->field($registration, 'password',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password', 'class' => 'md-input']) ?>

<?= $form->field($registration, 'password_repeat',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password_repeat', 'class' => 'md-input']) ?>

<?= $form->field($registration, 'email',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_email', 'class' => 'md-input']) ?>
<div class="uk-margin-medium-top">
<button class="md-btn md-btn-primary md-btn-block md-btn-large">Sign in</button>
</div>
<?php ActiveForm::end(); ?>

当我填写所有给定字段时,即使第一次是正确的,重复密码时也会出现错误密码不匹配。我的验证规则有问题还是 Yii Validator 中的错误?

UPD:我已尝试'skipOnError' => true。我发现它是类似问题的答案,但它仍然无法按预期工作。

UPD:我在控制台中做了一些验证:

var a = $('#register_password')
undefined
a.val()
"Halloha"
var b = $('#register_password_repeat')
undefined
b.val()
"Halloha"

但它仍然显示密码不匹配错误消息

最佳答案

尝试使用这样的规则

 // validates if the value of "password" attribute equals to that of 
['password', 'compare', 'message'=>"Passwords don't match"],

它会自动将密码值与属性password_repeat进行比较,而不是按照文档中所述的其他顺序进行比较。

http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#compare

关于php - 比较规则 yii2 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36501399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com