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.

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.