Custom validators for Zend_Form_Element

Christer has written a tutorial on writing custom validators for ZendFormElement.

He covers how to ensure that two fields are the same:

The thing I also want to do is to ensure that the two email elements have the same value. The same goes for the two password elements. To do this I had to write a custom validator for these cases. A similar validator can be found in the Zend_Form docs but I wanted to be able to specify the names of the element(s) an element must be equal to when I add the validator instead of hardcoding them in the validator classes (like the example in the docs does).

He includes full source for the work he’s done so it is easy to follow along.

Posted by Rob on 18th April 2008 under Around the web | 2 Comments »

2 Responses to “Custom validators for Zend_Form_Element”

  1. alidbc responded on 04 Jun 2008 at 9:45 pm #

    I think this is simpler and logical

    ‘Value Does not match its repeated value’); private $repeatedField; public function __construct($repeatedField){ $this->repeatedField = $repeatedField; }

    public function isValid($value, $context = null)
    {
        $value = (string) $value;
        $this->_setValue($value);
    
        if (is_array($context)) {
            if (isset($context["$this->repeatedField"])
                && ($value == $context["$this->repeatedField"]))
            {
                return true;
            }
        } elseif (is_string($context) && ($value == $context)) {
            return true;
        }
    
        $this->_error(self::NOT_MATCH);
        return false;
    }
    

    }

  2. alidbc responded on 04 Jun 2008 at 9:47 pm #

    class ValidateValueRepeat extends Zend_Validate_Abstract { const NOT_MATCH = ‘notMatch’; protected $_messageTemplates = array(self::NOT_MATCH => ‘Value Does not match its repeated value’); private $repeatedField; public function __construct($repeatedField){ $this->repeatedField = $repeatedField; }

    public function isValid($value, $context = null)
    {
        $value = (string) $value;
        $this->_setValue($value);
    
        if (is_array($context)) {
            if (isset($context["$this->repeatedField"])
                && ($value == $context["$this->repeatedField"]))
            {
                return true;
            }
        } elseif (is_string($context) && ($value == $context)) {
            return true;
        }
    
        $this->_error(self::NOT_MATCH);
        return false;
    }
    

    }