Custom Error Messages on Zend Form Validators

Zend Form is extremely powerful, and I love most of the built in validators. But some of the validators are overkill for many projects. Take the EmailAddress validator for instance. I have never worked on a web-form where I wanted 3 error messages to appear if the Email address entered was invalid. (To see what I mean, just type in “[email protected]” for your email address and see what Zend_Validate_EmailAddress displays). I have seen several questions and complaints about this problem (Example 1 or Example 2) and thought I would offer up my fix.

I have found that the quickest way to to control your error messages with the EmailAddress Validator is to create your own email validator that extends from Zend_Validate_EmailAddress, and then override the isValid function. Here is the shortest version I have come up with:

class Clint_Validate_EmailAddress extends Zend_Validate_EmailAddress
{
    public function isValid($value)
    {
       $response = parent::isValid($value);
       if(!$response){
           $this->_messages =
                array(self::INVALID => "Please enter a valid email address");
       }
       return $response;
    }
}

This class simply calls the parent function isValid(), and if it returns false, it sets the _messages array to have only one error message of your choice. Call it a hack if you want, but it works, and it works without putting logic in the controller which means I can re-use this form wherever I want. As always, let me know if you have a different and/or better way of doing this.

comments powered by Disqus