Custom Validators

I have a form where depending on the country selected from a drop down list the required fields change.

There are 4 fields, only two of which are used (the combination depending on the country selected). I use javascript to hide the fields that are not appropriate for the selected country. The 4 fields are not added to the CRequiredValidator since I dont want the form to fail when the fields that are hidden are not filled in.

I have coded a custom validator and it all works fine except for the fact that I want the label to display the * for the two fields which are visible. I can do this by not using $form->label and coding the html myself but that is a bit of a fudge and will no doubt break other things down the track.

This works :




            <label for="Recipient_AccountNumber" class="required">Account Number <span class="required">*</span></label>

    		<?php echo $form->textField($model,'AccountNumber',array('size'=>45,'maxlength'=>45)); ?>

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



and this doesnt display the * (not surpisingly since the field is not set to required)




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

    		<?php echo $form->textField($model,'IBAN',array('size'=>45,'maxlength'=>45)); ?>

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



What is the correct way to do this?

I don’t know if it’s the correct/cleanest way to do it, but you can override CModel::isAttributeRequired() in your model:




public function isAttributeRequired($attribute)

{

	return in_array($attribute, array('names', 'of', 'required', 'attributes') ? true : parent::isAttributeRequired($attribute);

}



Surely that wouldn’t work here? I want to specify different fields based on the value in another field in the same form.

There’s no easy way.

Check this topic and this extension for a starting point.