How to create client side self defined rule in yii
Asked Answered
H

2

6

I want to use reset password functionality in Yii. For that I have 4 fields i.e email, currentPassword, newPassword, newPasswordRepeat.

I have used 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 which checks whether currentPassword password match with my original password or not.

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 error on server side, i.e when I click on Submit button, page gets reloaded and then error gets displayed.

I want to display error on client side like other errors.

And I have enabled client side validation in form.

<?php $form=$this->beginWidget('CActiveForm', array(
      'id'=>'contact-form',
      'enableClientValidation'=>true,

      'clientOptions'=>array(
          'validateOnSubmit'=>true,
      ),
)); ?>
Hallerson answered 19/9, 2013 at 7:30 Comment(0)
B
0

Try to change

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

to

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

EDIT:

Also, you need AJAX validation:

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

and in top of your controller action:

if (array_key_exists('ajax', $_POST) && $_POST['ajax'] === 'contact-form') {
        echo CActiveForm::validate($model);
        Yii::app()->end();
}
Bulgaria answered 19/9, 2013 at 9:35 Comment(0)
G
0

Best way is to extend the CValidator class. Inside there you can override two methods validateAttribute and clientValidateAttribute. What you need is the second one. clientValidateAttribute. Make sure you have enable client side validation.

'enableClientValidation'=>true,

Sample:

class MyValidation extends CValidator
{

protected function validateAttribute($object,$attribute)
{
         //TODO: server side validation
}


public function clientValidateAttribute($object,$attribute)
{
    //TODO: client side javascript
}
}
Gules answered 14/1, 2014 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.