Custom Messages for Zend_Form_Element::addValidator

Today I wanted to change the custom validation error messages that are generated when using Zend_Form. This isn’t as easy as I first hoped, because even with all of the documentation on the ZF site, I still had some problems understanding exactly what the Zend_Validate class needed to receive in order to display my custom errors.

Basically, each ::addValidtor method takes 3 parametres, the type of validator, wether to break the chain on validation failiure,  and an array of custom options.  One of these options (messages) needs to be set in order for the form to display your custom messages. These messages take the form of a key=>value array where the key is they type of validation faliure (string of between 5 and 10 characters could be too short or too long), and the value is the custom error message.

For example:

->addValidator('stringLength', true, array('min'=>1, 'max'=>32, 'messages'=>array(Zend_Validate_StringLength::TOO_LONG =>'The maximum number of characters is %max%')))

This looks like a bit of a mess to me, so I decided to create an array of the messages arrays, and pass that to the options array instead.

One of the biggest changes to note, is that before I was using the custom messages, I was just passing the option parameters as values, and no in key=>value pairs. For example in the stringLength example above, my old code was:

->addValidator('stringLength', true, array(1,32))

In fact, once I got my head around having to pass the custom options as key=>value pairs, everything quickly fell into place.

As an extra aside, if you are using setRequired, and want to overwrite the default “Value is required and can’t be empty” message, simply add your own notEmpty validator with a custom error message as I’ve shown above.

For a list of constants each validator uses to put in your messages array see:

Your Comments are Awesome, Please Leave Them!

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s