表单元素上的Zend Framework自定义验证器

时间:2011-07-02 18:29:24

标签: zend-framework

您好我正在尝试以zend形式设置元素自定义验证器,这就是我所拥有的。

class Siteanalysis_Form_User_ChangePassword extends SA_Form_Abstract
{
  public function init()
  {

    // add path to custom validators
    $this->addElementPrefixPath(
        'Siteanalysis_Validate',
        APPLICATION_PATH . '/modules/siteanalysis/models/validate/',
        'validate'
    );

    $this->addElement('text', 'passwdVerify', array(
        'filters'    => array('StringTrim'),
        'validators' => array('PasswordVerification',array('StringLength', true, array(6, 128))),
        'decorators' => array('ViewHelper','Errors',
                        array('HtmlTag', array('id' => 'passwdVerify')),
                        array('Label', array('placement'=>'prepend','class'=>'label'))),
        'required'   => true,
        'label'      => 'Confirmar contraseña nueva',
    ));

     $this->addElement('submit', 'change', array(
        'label'      => 'Cambiar',
        'required' => false,
        'ignore'   => true,
        'decorators' => array('ViewHelper')
    ));     
  }
}


 class Siteanalysis_Validate_PasswordVerification extends Zend_Validate_Abstract
 {
   const NOT_MATCH = 'notMatch';

   protected $_messageTemplates = array(
     self::NOT_MATCH => 'Verifique que las contraseñs sean iguales.'
   );

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

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

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

问题是它没有调用PasswordVerification自定义验证器,是否有人看到它有问题?

感谢。

2 个答案:

答案 0 :(得分:0)

更新:测试设置

    $form = new Siteanalysis_Form_User_ChangePassword();

    $value = 'Adam';
    $data = array('passwdVerify' => $value);

    $validation = $form->isValid($data);
    if ( $validation === false ) {
        $element = $form->getElement('passwdVerify');
        $errors  = $element->getErrors();
        $msg     = $element->getMessages();
    } else {
        $values = $form->getValidValues($data);
    }

如果$ value是

  • 空我得到$ errors“isEmpty”
  • 'Adam'我收到$ error“noMatch”和“stringLengthTooShort”
  • 'AdamSandler'我得到$ error“noMatch”

答案 1 :(得分:0)

您的验证器数组应如下所示:

'validators' => array('PasswordVerification' => array('StringLength', true, array(6, 128)))

'validators', array('PasswordVerification',array('StringLength', true, array(6, 128))),