我是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.');
}
請幫助我。
顯示您的驗證功能(如喬恩下面指出的 - 它沒有驗證,但規則功能)從模型。它應該包含可能失敗的驗證規則。 – renathy
不是驗證函數 - 在你的驗證規則被定義的地方顯示'rules()'函數。你也可以'print_r($ model-> getErrors())'來確切地看到什麼不驗證以及爲什麼。 – Jon
也許你有更多的規則比強制性的,如整數類型...顯示規則plz – Pouki