12

In my form, I'm trying to verify that the user fills in the same value both times (to make sure they didn't make a mistake). I think that's what Zend_Validate_Identical is for, but I'm not quite sure how to use it. Here's what I've got so far:

$this->addElement('password', 'password', array(
        'label'      => 'Password:',
        'required'   => true,
        'validators' => array(
            'Identical' => array(What do I put here?)
        )
    ));
$this->addElement('password', 'verifypassword', array(
        'label'      => 'Verify Password:',
        'required'   => true,
        'validators' => array(
            'Identical' => array(What do I put here?)
        )
    ));

Do I need it on both elements? What do I put in the array?

1

7 Answers 7

28

For what its worth, support for comparing two identical form fields within a model was added to the 1.10.5 release. I wrote up a short tutorial on the matter, which you can access via the below link, but the bottom line is that the Zend_Validate_Identical validator has been refactored to accept a form field name as input. For instance, to compare the values of form fields pswd and confirm_pswd, you'll attach the validator to confirm_pswd like so:

$confirmPswd->addValidator('Identical', false, array('token' => 'pswd'));

Works like a charm.

See Validating Identical Passwords with the Zend Framework for a more complete example.

1
  • How can I use this for both add and edit operation @ Jason , @saji89
    – ehp
    Commented Sep 21, 2012 at 14:25
5

I can't test it at the moment, but I think this might work:

$this->addElement('password', 'password', array(
    'label'      => 'Password:',
    'required'   => true
));
$this->addElement('password', 'verifypassword', array(
    'label'      => 'Verify Password:',
    'required'   => true,
    'validators' => array(
        array('identical', true, array('password'))
    )
));
2
  • I'm getting the error: The token 'password' does not match the given token 'testpassword'. testpassword is the value and password is the name of the element that was specified here: 'identical', true, array('password')
    – Andrew
    Commented Oct 27, 2009 at 4:38
  • I was about to say that it was weird that it displayed the value of the password I entered in the error message, but turns out that's not true because I had set the element type as text and not password.
    – Andrew
    Commented Oct 27, 2009 at 4:40
2

After two days I found the right answer follow me step by step:

step 1:

create PasswordConfirmation.php file in root directory of your project with this path: yourproject/My/Validate/PasswordConfirmation.php with this content below:

<?php 
require_once 'Zend/Validate/Abstract.php';
class My_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
    const NOT_MATCH = 'notMatch';

    protected $_messageTemplates = array(
        self::NOT_MATCH => 'Password confirmation does not match'
    );

    public function isValid($value, $context = null)
    {
        $value = (string) $value;
        $this->_setValue($value);

        if (is_array($context)) {
            if (isset($context['user_password']) 
               && ($value == $context['user_password']))
            {
                return true;
            }
        } 
        elseif (is_string($context) && ($value == $context)) {
            return true;
        }

        $this->_error(self::NOT_MATCH);
        return false;
    }
}
?>

step 2:

Add two field in your form like this:

//create the form elements user_password
$userPassword = $this->createElement('password', 'user_password');
$userPassword->setLabel('Password: ');
$userPassword->setRequired('true');
$this->addElement($userPassword);

//create the form elements user_password repeat
$userPasswordRepeat = $this->createElement('password', 'user_password_confirm');
$userPasswordRepeat->setLabel('Password repeat: ');
$userPasswordRepeat->setRequired('true');
$userPasswordRepeat->addPrefixPath('My_Validate', 'My/Validate', 'validate');
$userPasswordRepeat->addValidator('PasswordConfirmation', true, array('user_password'));
$this->addElement($userPasswordRepeat);

now enjoy your code

1
  • @moinsam ,If I have an edit/update option along with add the what changes should be made ?
    – ehp
    Commented Sep 21, 2012 at 19:00
1
class My_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
const NOT_MATCH = 'notMatch';

protected $_messageTemplates = array(
    self::NOT_MATCH => 'Password confirmation does not match'
);

public function isValid($value, $context = null)
{
    $value = (string) $value;
    $this->_setValue($value);

    if (is_array($context)) {
        if (isset($context['password_confirm'])
            && ($value == $context['password_confirm']))
        {
            return true;
        }
    } elseif (is_string($context) && ($value == $context)) {
        return true;
    }

    $this->_error(self::NOT_MATCH);
    return false;
}
}

http://framework.zend.com/manual/en/zend.form.elements.html

1
$token = Zend_Controller_Front::getInstance()->getRequest()->getPost('password');
$confirmPassword->addValidator(new Zend_Validate_Identical(trim($token)))
                  ->addFilter(new Zend_Filter_StringTrim())
                  ->isRequired();   

Use the above code inside the class which extends zend_form.

2
  • cant we use $password->getValue() ? well i have already tried but i got empty value.. why is it so? if getValue is method of that element then it should have returned the value of the password? Commented Sep 5, 2013 at 12:41
  • that because getValue() is getting called before $form->isValid($_POST); since that code is inside constructor or init method .
    – Mr Coder
    Commented Sep 5, 2013 at 12:49
0

I was able to get it to work with the following code:

In my form I add the Identical validator on the second element only:

$this->addElement('text', 'email', array(
        'label'      => 'Email address:',
        'required'   => true,
        'filters'    => array('StringTrim'),
        'validators' => array('EmailAddress')
    ));

$this->addElement('text', 'verify_email', array(
        'label'      => 'Verify Email:',
        'required'   => true,
        'filters'    => array('StringTrim'),
        'validators' => array('EmailAddress', 'Identical')
    ));

And in the controller, just before calling isValid():

$validator = $form->getElement('verify_email')->getValidator('identical');
$validator->setToken($this->_request->getPost('email'));

I don't know if there is a more elegant way of doing this without having to add this code to the controller. Let me know if there is a better way to do this.

0

With Zend Framework 1.10 the code needed to validate the equality of two fields using Zend Form and Zend Validate is:

    $form->addElement('PasswordTextBox',
                      'password',
                      array('label'      => 'Password')
                      );

    $form->addElement('PasswordTextBox',
                      'password_confirm',
                      array('label'      => 'Confirm password',
                            'validators' => array(array('Identical', false, 'password')),
                            )
                      );

You can notice, in the validators array of the password_confirm element, that the Identical validator is passed as array, the semantics of that array is: i) Validator name, ii) break chain on failure, iii) validator options As you can see, it's possible to pass the field name instead of retrieving the value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.