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 “a@a” 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.
I like this solution, but it’s not going to work for some people. If you don’t want to extend the class, something I do recommend and enjoy in Zend, you can pass in messages on a per-element basis:
$element->addValidator(‘Between’, false, array(‘min’ => 1, ‘max’ => 65, ‘messages’ => ‘This is Required!’));
The only annoying part about this is that every element is slightly different in how it treats accepting messages.. mildly frustrating.
I like your solution!
Looks very efficient.
Thanks
What about overriding __construct and redefine protected variable $_messageTemplate?
class App_Validators_EmailValidator extends Zend_Validate_EmailAddress {
public function __construct($options = array())
{
parent::__construct($options);
$this->_messageTemplates = array(
self::INVALID => "My Custom 1",
self::INVALID_FORMAT => "My Custom 2",
self::INVALID_HOSTNAME => "My Custom 3",
self::INVALID_MX_RECORD => "My Custom 4",
self::INVALID_SEGMENT => "My Custom 5",
self::DOT_ATOM => "My Custom 6",
self::QUOTED_STRING => "My Custom 7",
self::INVALID_LOCAL_PART => "My Custom 8",
self::LENGTH_EXCEEDED => "My Custom 9",
);
}
}
@martin – That is another option, but it doesn’t change the fact that is will still throw up to three errors at a time, when maybe you only want one. If you look at the example 2 in my first paragraph you will see. Sometimes you may just want it to say “Invalid Email”.
how do I display all error messages?