Non Required Custom Validator

I have written a custom form validator to ensure that the data entered is a valid IP address for the organization that I am a part of. The problem is that I cannot make that field optional now.

Here is the basic class.




class IPAddressValidator extends CValidator{


    protected function validateAttribute($object, $attribute) {

        $ip = $object->$attribute;

        if(!IPAddress::is_valid_ip($ip))      

            $this->addError($object,$attribute,'Input value was not in the form of a valid IP address (example: 12.34.56.78)');

    }

}



The function IPAddress::is_valid_ip($ip) is something else that I wrote. It works great, but if you put in null or an empty string "" it returns false because obviously that is not a valid IP address.

When the user submits a form where the IP address information is optional, Yii assigns that attribute an empty string "" which is then passed to the custom validator IPAddressValidator::validateAtribute(). This returns an error to the user.

Is there a way I can tell it not to run this check when I don’t want this to be a required field? I could just modify the validateAttribute() function to return true if $attribute is null or empty string, but it seems like there should be a better way.

Oh, I figured it out. I guess I will write the answer here just in case anyone else ran into the same problem. Unlike what I said before the answer IS to just write the validator to accept null as an answer. This is the style that Yii validators handle this. Take a look any of the CValidator classes. They all have the following pieces of code




class CDateValidator extends CValidator

{

   ...

   

  /**

   * @var boolean whether the attribute value can be null or empty. Defaults to true,

   * meaning that if the attribute is empty, it is considered valid.

   */

   public $allowEmpty=true;


   ...

   

    protected function validateAttribute($object,$attribute)

    {

	$value=$object->$attribute;

	if($this->allowEmpty && $this->isEmpty($value))

		return;

        

        ... validation logic ...

    }


}



So you can see when validateAttribute() runs, if the attribute is null or empty string, it will return as true anyway.

I’m not sure you have to include $this->allowEmpty or if you can just type




if($this->isEmpty($value))

...


OR


if($value === null || $value === "")

...