Creating custom validation rule

Hello,

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!

CoLT

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

(not tested)

/Tommy

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

http://www.yiiframework.com/doc/api/CCompareValidator

or declaring your own function

http://www.yiiframework.com/doc/guide/form.model#declaring-validation-rules

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

http://www.yiiframework.com/doc/

hope it helps

:)

regards!!

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 ;)

Regards,

CoLT

Hi CoLT,

here’s a custom validator from phundament:

http://code.google.com/p/phundament/source/browse/trunk/modules/p2/validators/P2ArrayValidator.php

Best regards,

schmunk

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

Regards,

CoLT