PHPEye开源社区 » Zend Framework 使用讨论 » Zend Form 中如何验证2个password是否相同?
《Programming PHP》第二版上市
2008-7-16 13:02 zhex
Zend Form 中如何验证2个password是否相同?

Zend Form 中如何验证2个password是否相同?
网上找了好长时间都没有找到答案, 请这里的高手帮帮忙

2008-7-16 13:44 jasonqi
下面是我抄别人的,估计你还需要判断元素是否在表中存在等校验,照猫画虎就可以了


[php]<?php  
require_once 'Zend/Validate/Abstract.php';  
  
class My_Validate_Match extends Zend_Validate_Abstract
{  
    const NOT_MATCH = 'NotMatch';  
  
    protected $_messageTemplates = array(  
        self::NOT_MATCH => "'%fieldName%' does not match"
    );  
  
    /**
     * The fields that the current element needs to match
     *
     * @var array
     */  
    protected $_fieldsToMatch = array();  
  
    /**
     * Constructor of this validator
     *
     * The argument to this constructor is the third argument to the elements' addValidator
     * method.
     *
     * @param array|string $fieldsToMatch
     */  
    public function __construct($fieldsToMatch = array()) {  
        if (is_array($fieldsToMatch)) {  
            foreach ($fieldsToMatch as $field) {  
                $this->_fieldsToMatch[] = (string) $field;  
            }  
        } else {  
            $this->_fieldsToMatch[] = (string) $fieldsToMatch;  
        }  
    }  
  
    /**
     * Check if the element using this validator is valid
     *
     * This method will compare the $value of the element to the other elements
     * it needs to match. If they all match, the method returns true.
     *
     * @param $value string
     * @param $context array All other elements from the form
     * @return boolean Returns true if the element is valid
     */  
    public function isValid($value, $context = null) {  
        $value = (string) $value;  
        $this->_setValue($value);  
  
        $error = false;  
  
        foreach ($this->_fieldsToMatch as $fieldName) {  
            if (!isset($context[$fieldName]) || $value !== $context[$fieldName]) {  
                $error = true;  
                $errorMessage = $fieldName . ' does not match';
                $this->setMessage($errorMessage, self::NOT_MATCH);
                $this->_error(self::NOT_MATCH);  
                break;  
            }  
        }  
  
        return !$error;  
    }  
}  [/php]

页: [1]


Powered by Discuz! Archiver 5.5.0  © 2001-2006 Comsenz Inc.