سؤال

How can i set the identical validator on a field without making it a required field in Zendframework 1 + allow the check of empty value.

here is the code

     $this->addElement('password', 'password', array(            
        'label' => 'password',
         'required' => false            
        ),
    ));
    $this->addElement('password', 'confirm', array(
        'label' => 'confirm',
        'required' => false,
        'validators' => array(
            array(
                'validator' => 'Identical',
                'options' => array(
                    'token' => 'password'
                )
            )
        )
    ));

If the confirm element is set to 'required'=>false, the identical validator doesn't work if the value is empty.

هل كانت مفيدة؟

المحلول

You can't use Identical validator without required because in the isValid() method of Zend_Form_Element there is :

    if ((('' === $value) || (null === $value))
        && !$this->isRequired()
        && $this->getAllowEmpty()
    ) {
        return true;
    }

and Zend_Form_Element_Password is an instance of Zend_Form_Element.

I think you have 3 possibilities:

  1. Add required option in your confirm element, but you have a specific message required
  2. Add allowEmpty option to false in your confirm element like this : 'allowEmpty' => false, instead of 'required' => false,
  3. Create your own validator like the Cully Larson's answer. An other example it's the example #3 of the documentation about Writing validators. Otherwise, you can find more on the web. :)

نصائح أخرى

I ended up writing my own validator for password confirmation:

class MyLib_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
    const PASSWORD_MISMATACH = 'passwordMismatch';

    protected $_messageTemplates = array(
        self::PASSWORD_MISMATCH => 'This value does not match the confirmation value.'
    );

    /**
     * Requires that 'password_confirm' be set in $context.
     */
    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::PASSWORD_MISMATCH);
        return false;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top