Today I will talk about making custom validators in Zend Framework 1.10. Sometimes you need to validate something special that the standard built-in validators can not handle. This is the perfect time to make your own.
Custom validators are placed in the library section. In this example I put my new validator here: Library/My/Validator/CheckIfEmailIsUnique.php
class My_Validator_CheckIfEmailIsUnique extends Zend_Validator_Abstract { // Init error message variable const MSG_EMAIL_ALREADY_EXISTS = ""; // Set error msg in the message template (%value% will be replaced with indata email) protected $_messageTemplates = array( self::MSG_EMAIL_ALREADY_EXISTS => "'%value%' is already in use. Please choose another", );
// The only function we need to write is isValue public function isValid($email) { // This will replace the %value% with the tested email address in the error msg $this->_setValue($email); // Get the model $model = new Application_Model_Validator();
// Run the unique test in the model if($model->checkIfEmailIsUnigue($email)){ // Email is unique in the database - return true return true; } else { // Email is not unique //Set error message $this->_error(self::MSG_EMAIL_ALREADY_EXISTS); // Return false return false; } } }
To check if the email is unique I made a function in my validator model that checks the email agains those already in the database. If it finds the email it will return false and if not true
Application/Model/Validator.php
class Application_Model_Validator { public function __construct() { $this->_db = Zend_Registry::get('db'); } public function checkIfEmailIsUnique($email) { $query ="SELECT id FROM user WHERE email = '{$email}'"; $result = $this->_db->fetchOne($query); if(!$result){ return true; } else { return false; } } ... }
Now all we need to do is to add the new validator to our Zend_Form. We do this by first adding the path to the new validator (My/Validator/) and then add the new validator with the Zend_Element addValidator() function (the same way you add the built in validators).
Application/Forms/CreateAccount.php
class Application_Form_CreateAccount extends Zend_Form { ... public function init() { //Add path to custom validators - IMPORTANT $this->addElementPrefixPath('My_Validator', 'My/Validator/', Zend_Form_Element::VALIDATE); $email = new Zend_Form_Element_Text('email'); $email->setLabel('E-mail:') ->setRequired(true) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('EmailAddress', true) ->addValidator('CheckIfEmailIsUnique');//Here I add the new validator ... } }
Since I do not validate the email format in my new validator I use the built-in validator EmailAddress and set the second argument to true. This means that if the EmailAddress validator returns false our CheckIfEmailIsUnique will not be run at all. The element will return the error and stop executing.
Hope this will help you understand how to make your own custom validators in Zend Framework
0 Comments.