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.