Zend_Form is awesome. Zend_Validate and Zend_Filter are awesome. The Error decorators are also awesome, but sometimes a little too awesome.

I mean, when a user leaves an email field blank, and I had a NotEmpty and EmailAddress validator, I get two error messages!

  • Value is required and can't be empty
  • '' is no valid email address in the basic format local-part@hostname

Really I’d rather it just said:

  • Please enter a valid email address

Because some users, lets face it, are idiots! Nice idiots, but idiots all the same lol!

To stop this sort of thing happening, you can say in your form element:

$email = new Zend_Form_Element_Text('email');
 $email->setRequired(true)
 ->addFilter('StripTags')
 ->addFilter('StringTrim')
 ->addValidator('NotEmpty',true)
 ->addValidator('EmailAddress')
 ->setLabel('Email')
 ->setErrorMessages(array('Please enter a real email address'));

The key thing here is the true value in the NotEmpty validator. It breaks the chain of validators upon failure, stopping subsequent validators from checking and adding its error message too.
Without the true, but with the custom error message, you would get:

  • Please enter a valid email address
  • Please enter a valid email address

This should help save headaches!