Compare Two Fields

In Yii, the compare used for comparing two form fields. i want to compare two fields in the form,but if they are equal shows error message. Whats the solution for ajax validation in this case?

Does this help?

But its useful for ajax validation?

As far as I can see it should work.

How it will work? when it define in a model?

Dear Friend

What Keith pointed out is absolutely correct.

Here is an example.



class CompareForm extends CFormModel


	public $username1;

	public $username2;


	public function rules()


		return array(

			array('username1,username2', 'required'),

			array('username2', 'compare','compareAttribute'=>"username1",'operator'=>"!="),		






public function actionCompare(){

	$model=new CompareForm;




           // $model->attributes=$_POST["CompareForm"];






protected function performAjaxValidation($model)


		if(isset($_POST['ajax']) && $_POST['ajax']==='compare-form')


			echo CActiveForm::validate($model);





<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(



)); ?>

	<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,'username1'); ?>

		<?php echo $form->textField($model,'username1'); ?>

		<?php echo $form->error($model,'username1'); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'username2'); ?>

		<?php echo $form->textField($model,'username2'); ?>

		<?php echo $form->error($model,'username2'); ?>


	<div class="row buttons">

		<?php echo CHtml::submitButton('Save'); ?>


<?php $this->endWidget(); ?>

Here I enabled ajaxValidation only.

When two fields have same input, the error is thrown below second field.

When user changes the first input, error will not disappear.

You have to change input in the second field to hide or display error.


Thanks Keith and seenivasanā€¦ it works fineā€¦:)