我将此类添加到library / My / Validate / PasswordConfirmation.php
<?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['password'])
&& ($value == $context['password']))
{
return true;
}
} elseif (is_string($context) && ($value == $context)) {
return true;
}
$this->_error(self::NOT_MATCH);
return false;
}
}
?>
然后我在我的表单中创建两个字段:
$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', 'password_confirm');
$userPasswordRepeat->setLabel('Password repeat: ');
$userPasswordRepeat->setRequired('true');
$userPasswordRepeat->addPrefixPath('My_Validate','My/Validate','validate');
$userPasswordRepeat->addValidator('PasswordConfirmation');
$this->addElement($userPasswordRepeat)
一切都很好,但是当我提交表单时,我会收到“密码确认不匹配”的消息?我的代码中有什么错误
答案 0 :(得分:17)
您不需要覆盖Zend_Form-&gt; isValid方法或使用超全局$ _POST,请检查:
$frmPassword1=new Zend_Form_Element_Password('password');
$frmPassword1->setLabel('Password')
->setRequired('true')
->addFilter(new Zend_Filter_StringTrim())
->addValidator(new Zend_Validate_NotEmpty());
$frmPassword2=new Zend_Form_Element_Password('confirm_password');
$frmPassword2->setLabel('Confirm password')
->setRequired('true')
->addFilter(new Zend_Filter_StringTrim())
->addValidator(new Zend_Validate_Identical('password'));
答案 1 :(得分:8)
一种不那么优雅和简单的方法:
$password = new Zend_Form_Element_Password('password');
$password->setLabel('Password:')
->addValidator('StringLength', false, array(6,24))
->setLabel('Choose your password:')
->setRequired(true);
$password2 = new Zend_Form_Element_Password('password-confirm');
$password2->setLabel('Confirm:')
->addValidator('StringLength', false, array(6,24))
->setLabel('Confirm your password:')
->addValidator(new Zend_Validate_Identical($_POST['password']))
->setRequired(true);
答案 2 :(得分:3)
有一种更好的方法可以做到这一点。在您的表单中将相同的验证器放在确认passoword字段上,然后只需覆盖$ form-&gt; isValid()方法来设置要验证的值:
public function __construct($options = NULL)
{
// ...
$confirm->addValidator('Identical');
// ...
}
public function isValid($data)
{
$confirm = $this->getElement('confirm_password');
$confirm->getValidator('Identical')->setToken($data['password']);
return parent::isValid($data);
}
答案 3 :(得分:2)
我认为您可能需要$context['user_password']
,因为这是您的“第一个”密码元素的名称
答案 4 :(得分:2)
使验证器可重用。不要在验证器中硬编码字段名称。看看这个更普遍的IdenticalField Validator。