Checking that a password is repeated correctly using Zend_Validate_Identical
Sunday, August 1, 2010

When a user is asked to enter a new password, it is customary to ask the user to repeat it, in order to reduce the risk of it being entered incorrectly. In the Zend Framework, there is a validator that can check whether two items are identical, but using it with Zend_Form is tricky, because it needs the values of two fields to make the comparison, while validators are attached to a single field, independently of the others. This article looks at how to use Zend_Validate_Identical with Zend_Form.

Let us assume that we are adding our password and password repeat fields in the init method of our form class, which is derived from Zend_Form:

    $this->addElement(
      'password', 'password', array(
        'label'      => 'Password:',
        'maxLength'    => 64,
        'required'    => true,
        'decorators'  => $this->getFieldDecorators(),
        'errorMessages'  => array('Please enter a password')
      )
    );
 
    $this->addElement(
      'password', 'repeat_password', array(
        'label'      => 'Repeat Password:',
        'maxLength'    => 64,
        'required'    => true,
        'decorators'  => $this->getFieldDecorators(),
        'errorMessages'  => array('Please repeat the password correctly')
      )
    );

Note that both fields have the required option set to true; this is necessary event in the case of the repeat_password field, where we will be adding another validator later on. Also note that we have specified custom error messages for both fields, since the default messages are not appropriate.

The second and final step is to override the isValid method of the form class, and add the validator there:

  public function isValid($data)
  {
    $this->getElement('repeat_password')->
      addValidator(new Zend_Validate_Identical($data['password']));
 
    return parent::isValid($data);
  }

It is necessary to do it at this point, since it is only then that we have access to the value of the password field.

The form will now fail to validate if the password is not repeated correctly, and the appropriate error message will be generated.

Posted by James at 10:41 am   1 comment

One Response to “Checking that a password is repeated correctly using Zend_Validate_Identical”

Leave a Reply