Zend_Form: how to check 2 fields are identical

Ivo Trompert picture Ivo Trompert · Dec 7, 2008 · Viewed 13.4k times · Source

I have created a form to add a user to a database and make user available for login.

Now I have two password fields (the second is for validation of the first). How can I add a validator for this kind of validation to zend_form?

This is my code for the two password fields:

    $password = new Zend_Form_Element_Password('password', array(
        'validators'=> array(
            'Alnum',
            array('StringLength', array(6,20))
            ),
        'filters'   => array('StringTrim'),
        'label'     => 'Wachtwoord:'
        ));

    $password->addFilter(new Ivo_Filters_Sha1Filter());

    $password2 = new Zend_Form_Element_Password('password', array(
        'validators'=> array(
            'Alnum',
            array('StringLength', array(6,20))
            ),
        'filters'   => array('StringTrim'),
        'required'  => true,
        'label'     => 'Wachtwoord:'
        ));
    $password2->addFilter(new Ivo_Filters_Sha1Filter());

Answer

Tim Lytle picture Tim Lytle · Sep 23, 2010

The current version of Zend_Validate has this built in - while there are plenty of other answers, it seems that all require passing a value to Zend_Validate_Identical. While that may have been needed at one point, you can now pass the name of another element.

From the Zend_Validate section of the reference guide:

Zend_Validate_Identical supports also the comparison of form elements. This can be done by using the element's name as token. See the following example:

$form->addElement('password', 'elementOne');
$form->addElement('password', 'elementTwo', array(
    'validators' => array(
        array('identical', false, array('token' => 'elementOne'))
    )
));

By using the elements name from the first element as token for the second element, the validator validates if the second element is equal with the first element. In the case your user does not enter two identical values, you will get an validation error.