Zend_Validate supplies a set of commonly needed validators, but inevitably, developers will wish to
write custom validators for their particular needs. The task of writing a custom validator is
facilitated by implementing Zend_Validate_Interface
.
Zend_Validate_Interface
defines two methods, isValid()
and
getMessages()
, that may be implemented by user classes. An object that implements this
interface may be added to a validator chain with Zend_Validate::addValidator()
.
The following example demonstrates how a custom validator might be written:
<?php require_once 'Zend/Validate/Interface.php'; class MyValidator implements Zend_Validate_Interface { protected $_messages = array(); public function isValid($value) { $this->_messages = array(); // arrive on $requirement based on validation criteria if (!$requirement) { $this->_messages[] = "Reason validation failed"; return false; } return true; } public function getMessages() { return $this->_messages; } } ?>
To add an instance of the above validator to a validator chain:
<?php $validatorChain = new Zend_Validate(); $validatorChain->addValidator(new MyValidator()); ?>