How to create your own client side user rule in yii

I want to use the reset password functionality in Yii. For this, I have 4 fields ie email, currentPassword, newPassword, newPasswordRepeat.

I used the following rules in my model

array('email, currentPassword, newPassword, newPasswordRepeat', 'required'), array('newPasswordRepeat', 'compare', 'compareAttribute'=>'newPassword'), array('currentPassword', 'equalPasswords'), 

where equalPasswords is my user-defined rule that checks if the password currentPassword password of my original password.

 public function equalPasswords($currentPassword) { $oDbConnection = Yii::app()->db; $oCommand = $oDbConnection->createCommand('SELECT * FROM Superadmin_details where email=:email'); $oCommand->bindParam(':email', Yii::app()->session['email'],PDO::PARAM_STR); $user=$oCDbDataReader = $oCommand->queryRow(); if ($user['password'] != $currentPassword) $this->addError($currentPassword, 'Old password is incorrect.'); } 

This rule gives an error on the server side, i.e. when I click the submit button, the page reloads and then an error message appears.

I want to show the error on the client side, as well as other errors.

And I included client side validation in the form.

 <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'contact-form', 'enableClientValidation'=>true, 'clientOptions'=>array( 'validateOnSubmit'=>true, ), )); ?> 
+6
source share
2 answers

Try to change

 $this->addError($currentPassword, 'Old password is incorrect.'); 

to

 $this->addError('currentPassword', 'Old password is incorrect.'); 

EDIT:

Also, you need an AJAX check:

 <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'contact-form', 'enableClientValidation'=>true, 'enableAjaxValidation' => true, 'clientOptions'=>array( 'validateOnSubmit'=>true, ), )); ?> 

and at the top of your controller action:

 if (array_key_exists('ajax', $_POST) && $_POST['ajax'] === 'contact-form') { echo CActiveForm::validate($model); Yii::app()->end(); } 
0
source

The best way is to extend the CValidator class. Inside, you can override the two methods validateAttribute and clientValidateAttribute. You need a second. clientValidateAttribute . Make sure you enable client-side validation.

 'enableClientValidation'=>true, 

Example:

 class MyValidation extends CValidator { protected function validateAttribute($object,$attribute) { //TODO: server side validation } public function clientValidateAttribute($object,$attribute) { //TODO: client side javascript } } 
0
source

Source: https://habr.com/ru/post/954142/


All Articles