Zend 1,相同的验证器,无需要

时间:2014-05-08 07:43:53

标签: php zend-framework

如何在字段上设置相同的验证器而不使其成为Zendframework 1中的必填字段+允许检查空值。

这是代码

     $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'
                )
            )
        )
    ));

如果确认元素设置为' required' => false,则相同的验证器在值为空时不起作用。

2 个答案:

答案 0 :(得分:0)

我最后编写了自己的验证码来确认密码:

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;
    }
}

答案 1 :(得分:0)

您不能在required之后使用相同的验证码,因为在isValid()的{​​{1}}方法中有以下内容:

Zend_Form_Element

if ((('' === $value) || (null === $value)) && !$this->isRequired() && $this->getAllowEmpty() ) { return true; } Zend_Form_Element_Password的一个实例。

我认为你有三种可能性:

  1. Zend_Form_Element元素中添加required选项,但您需要具体的消息
  2. confirm元素中将allowEmpty选项添加为false,如下所示:confirm代替'allowEmpty' => false,
  3. 创建自己的验证器,如Cully Larson的答案。另一个例子是关于Writing validators的文档的'required' => false,。否则,您可以在网上找到更多信息。 :)
相关问题