How to set custom error messages in Zend standard validators

Quite often you would want to customize the error message from a validator. One good example is the Zend_Validate_Identical which standard message is something like ‘The two given tokens do not match’. That does not make much sense for the user trying to create an account on a site.

First we need to know what the message variables are called i the validator class. The easiest way to find this is simply to open the class file in Zend Framework for that validator. Validator classes can be found in Zend/Validate/ folder. We look inside the Zend/Validate/Identical.php;

...
class Zend_Validate_Identical extends Zend_Validate_Abstract
{
    /**
     * Error codes
     * @const string
     */
    const NOT_SAME      = 'notSame';
    const MISSING_TOKEN = 'missingToken';

    /**
     * Error messages
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_SAME      => 'The two given tokens do not match',
        self::MISSING_TOKEN => 'No token was provided to match against',
    );
...

Here we can see the variables are called: NOT_SAME and MISSING_TOKEN. We will use this knowledge to set our own messages. In our Zend_Form (eg. application/forms/CreateAccount.php)

...
$password = new Zend_Form_Element_Password('password');
$password ->setLabel('Password:')
->setDecorators($this->elementDecorators)
->setDescription('3 to 30 characters in length')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('StringLength', false, array(3, 30));

$confirm = new Zend_Form_Element_Password('confirm');
$confirm->setLabel('Confirm password:')
->setDecorators($this->elementDecorators)
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->setAttrib('size', '20')
->addValidator('StringLength', false, array(3, 30))
->addValidator('Identical', false, array('token' => 'password',
   'messages' => array(Zend_Validate_Identical::NOT_SAME => 'Passwords does not match', Zend_Validate_Identical::MISSING_TOKEN => 'No password was provided')));
...

The argument ‘messages’ in the Validator settings opens up the possibility to set your own messages like above.

Comments are closed.

Niklas Tech Blog
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.