Category Archives: PHP - Page 7

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.

Custom Zend Form rendering using view scripts

There are times when the ordinary decorators just is not enough for your forms. I had one project where we used clickable images to affect the contents of our form element. These images needed to be embedded into the form. Doing this with decorators turned out to be complicated so we used custom view scripts instead. It gave much more readable code.

Here is a small example in Zend Framework 1.10

First we need a form (application/forms/Login.php):

class Application_Form_Login extends Zend_Form {

    public function init() {

        $this->setName('login');

        $email = new Zend_Form_Element_Text('email');
        $email->addValidator('EmailAddress')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim');

        $pass = new Zend_Form_Element_Password('pass');
        $pass ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim');

        $submit = new Zend_Form_Element_Submit('login');
        $submit->setLabel('Login');      

        $this->addElements(array($email, $pass, $submit));
    }
}

Then we create the view script (application/views/scripts/index/loginForm.phtml):

Login/E-mail: element->email ?>
Password: <?php echo $this->element->pass ?>
<?php echo $this->element->login ?>

And finally we link them together. First we set the the path to the view script in the form (application/forms/Login.php). I do this because I do not want to put it in the default location (application/view/scripts)

...
$this->setDecorators(array(
      array('viewScript', array('viewScript' => 'index/loginForm.phtml'))
      ));
...

Then we tell the elements that they are going to use the script when rendering (application/forms/Login.php)

...
$email->addValidator('EmailAddress')
           ->setDecorators(array('ViewHelper'))
           ->setRequired(true)
...
...
$pass ->setRequired(true)
          ->setDecorators(array('ViewHelper'))
          ->addFilter('StripTags')
...

That’s it!

Check confirm password field using Zend_Validate_Identical

This validator was added in Zend Framework 1.10.5 and it has the ability to check if two fields are identical. Very useful for checking that the confirm password field contains the same characters as the password e.g. in a create account form. As with all the standard Zend validators this is very simple

...
$password = new Zend_Form_Element_Password('password');
$password->setLabel('Password:')
         ->setRequired(true)
         ->addFilter('StripTags')
         ->addFilter('StringTrim')
         ->setAttrib('size', '20')
         ->addValidator('StringLength', false, array(3, 30));

$confirm = new Zend_Form_Element_Password('confirm');
$confirm->setLabel('Confirm password:')
        ->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'));
...

Here I have added the Identical validator to the confirm element. The ‘token’ is the element name of the field to check, in this case the element above called ‘password’.

To set a custom error message you just set the Zend_Validate_Identical::NOT_SAME variable. This will show if the passwords in the two fields does not match. You can also set the Zend_Validate_Identical::MISSING_TOKEN to a message to show if no password was entered.