gpt4 book ai didi

php - $model-validation() 在 yii 中总是返回 false?

转载 作者:行者123 更新时间:2023-12-01 22:39:02 26 4
gpt4 key购买 nike

我是 YII 框架的新手。我正在编写一个更改密码的简单方法,我想验证控件,例如如果为空则显示错误消息,或者如果密码和重新输入的密码不匹配则显示错误。我已经使用下面的代码来做到这一点:

public function actionChange()
{
$model=new Users;
$model->scenario='change';
if (isset($_POST['Users'])) {
$model->setAttributes($_POST['Users']);

if($model->validate())
{
print "true";
}
else{

print "false";
}

if($model->validate())
{
$pass = md5($_POST['Users']['newPassword']);
$userModel = Users::model()->findByPk(Yii::app()->user->id);
$userModel->password = $pass;
$data = $userModel->update();
}

if(isset($data))
{
Yii::app()->user->setFlash('success',"Password changed successfully!");
$this->redirect(array('Users/change'), true);
}
}


$this->render('change_password', array('model'=>$model,true));
}

但是 **$model->validate()** 无论我是否填写字段,总是返回 false。

更新:

这里是规则函数:

public function rules()
{
return array(
array('is_active', 'numerical', 'integerOnly'=>true),
array('first_name, joining_date,last_name, employee_code, username, password, role', 'required'),
array('employee_code', 'numerical', 'integerOnly'=>true),
array('username','email'),
array('username','valid_username','on'=>array('create')),

//array('username', 'contraints', 'readOnly'=>true, 'on'=>'update'),

array('currentPassword, newPassword, newPasswordRepeat', 'required','on'=>array('change')),
//array('newPassword', 'length', 'min' => 6, 'max'=>20, 'message'=>Yii::t("translation", "{attribute} is too short.")),
//array('newPassword','ext.SPasswordValidator.SPasswordValidator', 'preset' => 'strong', 'max' => 41),
array('newPassword', 'compare', 'compareAttribute'=>'newPasswordRepeat','on'=>array('change')),
array('currentPassword', 'equalPasswords','on'=>array('change')),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>array('forgotPassword')),
array('joining_date', 'safe'),
array('user_id, first_name, last_name, employee_code, username, password, role, joining_date, pending_regular_leave, pending_medical_leave, allocated_regular_leave, allocated_medical_leave, is_active', 'safe', 'on'=>'search'),
);
}


public function equalPasswords($attribute, $params)
{
$user = Users::findByPk(Yii::app()->user->id);
if ($user->password != md5($this->currentPassword))
$this->addError($attribute, 'Old password is incorrect.');
}

请帮助我。

最佳答案

由于某种原因,您的验证失败。尝试在 else block 中显示验证错误(验证失败时)。

 if($model->validate()) {
....
}
else {
$errors = $model->getErrors();
var_dump($errors); //or print_r($errors)
exit;
}

另一件事,如果它没有帮助,您可以尝试从您的规则中注释一些验证规则,看看哪些规则失败了。

关于php - $model-validation() 在 yii 中总是返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17835854/

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