我是Yii的新手。我正在爲用戶進行更改密碼頁面。當我得到驗證時,我遇到了麻煩。Yii自定義驗證和服務器端驗證?
這是視圖:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'changepassword-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'old_pwd'); ?>
<?php echo $form->textField($model,'old_pwd'); ?>
<?php echo $form->error($model,'old_pwd'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pwd'); ?>
<?php echo $form->textField($model,'pwd'); ?>
<?php echo $form->error($model,'pwd'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pwd_repeat'); ?>
<?php echo $form->passwordField($model, 'pwd_repeat'); ?>
<?php echo $form->error($model,'pwd_repeat'); ?>
<p class="hint">
Passwords must be minimum 6 characters and can contain alphabets, numbers and special characters.
</p>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Change Password'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
型號:
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('user, pwd, status, old_pwd, pwd_repeat', 'required'),
array('user', 'length', 'max'=>50),
array('pwd', 'length', 'max'=>30),
array('status', 'length', 'max'=>10),
array('pwd','compare'),
array('old_pwd','checkOldPassword'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, user, pwd, status', 'safe', 'on'=>'search'),
);
}
// FOR CHECKING IF THE PASSWORD IS VALID
public function checkOldPassword($attribute,$params)
{
$record=Admin::model()->findByAttributes(array('pwd'=>$this->attribute));
if($record===null){
$this->addError($attribute, 'Invalid password');
}
}
控制器:
/**
* Change Password for users
*/
public function actionChangePassword()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
if(Yii::app()->user->isGuest){
// If the user is guest or not logged in redirect to the login form
$this->redirect(array('site/login'));
}
else{
$model = new Admin;
if(isset($_POST['Admin'])){
$model->attributes=$_POST['Admin'];
$this->render('changepassword',array('model'=>$model));
}
else{
$this->render('changepassword',array('model'=>$model));
}
}
}
我使用自定義驗證器'checkOldPassword'用於檢查用戶的當前密碼。現在的問題是,自定義驗證不起作用。此外,如果我關閉javascript 我發現服務器端驗證錯誤也不顯示。 Iam是Yii的新人。所以請原諒任何愚蠢的錯誤。 請幫忙。
「不工作「究竟如何? – Jon 2012-01-12 15:08:41
@Jon自定義驗證器不顯示任何錯誤。另外,當我在瀏覽器中禁用Javascript時,它不會顯示任何驗證錯誤,即使除了自定義驗證之外的驗證規則也不會顯示。 – ajaybc 2012-01-12 15:19:43