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.

  1. im able to get NOT_SAME message but im not getting message for Missing_token though password field is empty, how can i solve this using Identical validator.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.