Category Archives: Zend Framework - Page 4

Check confirm password field using Zend_Validate_Identical

This validator was added in Zend Framework 1.10.5 and it has the ability to check if two fields are identical. Very useful for checking that the confirm password field contains the same characters as the password e.g. in a create account form. As with all the standard Zend validators this is very simple

...
$password = new Zend_Form_Element_Password('password');
$password->setLabel('Password:')
         ->setRequired(true)
         ->addFilter('StripTags')
         ->addFilter('StringTrim')
         ->setAttrib('size', '20')
         ->addValidator('StringLength', false, array(3, 30));

$confirm = new Zend_Form_Element_Password('confirm');
$confirm->setLabel('Confirm password:')
        ->setRequired(true)
        ->addFilter('StripTags')
        ->addFilter('StringTrim')
        ->setAttrib('size', '20')
        ->addValidator('StringLength', false, array(3, 30))
        ->addValidator('Identical', false, array('token' => 
                     'password', 'messages' => 
                     array(Zend_Validate_Identical::NOT_SAME => 
                     'Passwords does not match'));
...

Here I have added the Identical validator to the confirm element. The ‘token’ is the element name of the field to check, in this case the element above called ‘password’.

To set a custom error message you just set the Zend_Validate_Identical::NOT_SAME variable. This will show if the passwords in the two fields does not match. You can also set the Zend_Validate_Identical::MISSING_TOKEN to a message to show if no password was entered.

Redirection in Zend Framework

Quite often you need to redirect to another controller/action after a decision in the controller. Sometimes you need to redirect to a whole different site. This is how I do redirects in Zend Framework 1.10:

Redirect to another controller and/or action
For this I use the Zend_Controller_Action_Helper function redirector(action, controller name)

$this->_helper->redirector('display', 'index');

This will redirect to the displayAction in the indexController

Redirect to another site
For this I use the Zend_Controller_Action function redirect(url). The redirect function takes an full url as input (you can also supply an array with redirect options)

$this->_redirect('http://framework.zend.com/');

This will redirect you to the Zend Framework site

How to make a custom validator:CheckIfEmailIsUnique

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