Yii Framework Forum: Style Question About Validators - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Style Question About Validators How Should I Handle Blank Data in Custom Validators Rate Topic: -----

#1 User is offline   MadSkillsTisdale 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 101
  • Joined: 15-February 09
  • Location:New Orleans, LA

Posted 01 June 2010 - 03:39 PM

I wrote a custom date validator, and I did a lot of checking to see if a value was blank before parsing it. This got me thinking:

If I return false on a blank value, then I am essentially making this field a required field if I want to validate it as a date field. This feels wrong.

If I do not return false on a blank value, then I am saying that an empty string is a valid date, and that also feels wrong.


What is the style guideline on handling this issue? Will my date validator only be called if there is data in the attribute, or should I return true on empty values and let the required validator handle it otherwise?



Thanks,
Corey
0

#2 User is offline   MadSkillsTisdale 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 101
  • Joined: 15-February 09
  • Location:New Orleans, LA

Posted 07 June 2010 - 09:51 PM

Solution found!

Make your validator work like this (I did not test this, just wrote it by hand in the forum, so there may be typos):



class MyValidator extends CValidator
{
   public $allowEmpty=true;
	

   protected function validateAttribute($model,$attribute) {

      if($this->allowEmpty && $this->isEmpty($value)) {
         return;
      }

      if(stuff is valid) {
         return true;
      }

      $errorMessage = "Stuff wasn't valid";
      $model->addError($attribute,$errorMessage);
      
      return false;
   }
    
}


0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users