jQuery and Required form fields

This one should work:




public function carMakeCheck()

{

  $validator=new CRequiredValidator;

  $validator->attributes= array('car_make');

  if ($this->vehicle_type=='car')

     $validator->validate($this, array('car_make'))

      

}



Is much more complex than how I thought initialy, maybe CRequiredValidator is not thought to be used like that…

Perfect! That’s exactly the solution I’ve been after for the past 2-3 days!

No need for scenarios or adding errors in manually! :)

edit: was going to post an improvemnt but would have been fruitless :)

btw: solution had already been posted! you just failed to notice it! Imagine you had to check many more options! would you rather write 100 "if" statements or put them into rules?

Dude, super disapointed it took you so long, don’t worry it happens, 5 min problem into xx days has happend to many people, just don’t make a regular thing…

No worries bro, appreciate the help :)

n/p i’m sure you do!

BTW is there any reason you say not to use afterValidate() function? I think it makes it a lot easier as I can set the attribute as ‘required’ in the rules and then do a simple check for the condition for when it needs to be required. And then use clearErrors() where needed.

With your solution above, theer is more code/processing and then I also have to manually define the attribute as ‘required’.

Also I found that if I want to validate multiple attributes on a custom function, each attribute will get validated multiple times! I.e 3 attributes = 3 x validation for each attribute.

You can use afterValidate as well, there are no difference.

My suggestion was just because I consider more polite use the ‘standard instrument’ like rules instead of override the framework function, but is a pure question of style, no difference at all.

If you get validate many time is because you set the rule for more 3 attributes, so the rule will be applied to all attributes, 3 times. You have 2 options: create an attribute depending validate function or create a single function for all field to validate (function to be called once, so only one attribute should figure in rules).

Attribute depending is like that:




public function carCheck($attribute)

{

   if ($this->vehicle_type=='car')

   {

        $validator=new CRequiredValidator;

	$validator->attributes=array($attribute);

	$validator->validate($this);

   }      

}



Like that carCheck is a ‘conditional required’, you can add as parameters you want and they will be checked if vehicle car is selected. You will add all attributes in rule like all standard rules.

Note that if more than one vehicle type is selected and all this vehicle type require an attribute, them the attribute will validated more than one time.

If you are in this situation is better to write a single function for all ‘conditional required’ field, create an array of field to validate and validate them all one time.