Creating custom validation rule


I have one problem, in Create view I need to check two date attributes.

SBeg(Begin) must be earlier date than SEnd(End).

How would this validator look like?

Thanks for help in advance!


I would consider to use CCompareValidator (and extend it if neccessary). There’s a builtin comparison ‘operator’ attribute.

(not tested)


if you want to perform the validation in the view, you should use javascript but if you want to perform the validation in your model or activeform I think that the following links will help you:

by using comparevalidator

or declaring your own function

also, take a look at the pdf file cheat sheet for validators, here

hope it helps



Oh really in this case its already done ;)

If anyone needs a sample:

	public function rules()


		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(


						array('SEnd','compare','compareAttribute'=>'SBeg','operator'=>'>', 'allowEmpty'=>false , 'message'=>'{attribute} must be greater than "{compareValue}".', 'on'=>'create, update'),




Thanks for good advice :D

By the way, I need some custom validator in more complex situation too.

Like: When adding a record in Course(table) I need to check whether Trainer and Branch does not have any courses in time range of Course length (I use two attributes for this CrTime (date) (hh:mm:ss) and CrLength (int) (minutes)).

I believe I should do a check first for either Trainer or Branch to find out whether there is a time Gap and new inserted course would not duplicate time schedule. Mostly it should be more an advice error, because in business rule - two Courses may be on same time in same Branch - so the user decide to leave the inserted record or fix until error stops bugging.

Any ideas, examples? I appreciate your help and hope these examples should be put in Cookbook "Creating custom Validator"

[edit] @scoob.junior

Yep already looked up those links;) practical examples in manipulating validation from two or more models would be good article in cookbook. As for the beginning simple custom validation should also drag user to know Yii deeper ;)



Hi CoLT,

here’s a custom validator from phundament:

Best regards,


Very good ;) Where do you use it?? (code sample)