Yii 1.1: switch-validator

Apply different sets of rules depending of an attribute's value. Pretty much like a php switch statement.

This is a validation that depending on the attribute value can apply other validators (not necessary on the same attribute).


tested with Yii 1.1.12 but should work with all Yii 1.1.*


The validator contains 2 attributes, one for the choices (cases) that the attribute can have and one when the validators that will be applied when none of the cases were matched ( default keyword when using a switch )

So imagine that you want to do a validation like this. You have an attribute type that is the type of the file to upload, and depending the type you want to apply certain validations to the file field (or different like the case). Given this stage you should put something like this in your rules function.

//... more rules validators here
array('type', 'ext.validators.FSwitchValidator', 
                array('file',  'required')
                array('file',  'file', 'types'=>'jpg,png') 
               array('url', 'required'),
               array('url', 'validVideoUrl'),
        'default'=>array('url', 'url', 'defaultSchema'=>'http') //simple array if only one validator
  //... more rules validators here

Total 3 comments

#10001 report it
onemoverx at 2012/09/27 11:11pm
RE: YiiConditionalValidator

The difference is obvious in my opinion, every switch can be expressed as a chain if statements. Of course I think the new YiiConditionalValidator is awesome (and thanks for pointing this because I didn't knew about the last update, which I think can be more complete with the else clause) but for this kind of checking I think its too complicated.

#9987 report it
Maxxer at 2012/09/27 08:22am

what's the difference with this? Thanks!

#9975 report it
Raoul at 2012/09/26 04:52am
very useful

I'll definitly try it ! Thanks

Leave a comment

Please to leave your comment.

Create extension