Joakim Nygård Archive Linked About

A Validator for URIs in Zend Framework

20 Feb 2009

Working with forms in Zend Framework is incredibly easy with the Zend_Form component. In some cases user input from forms contain URIs, e.g. for homepages. Though there is a Zend_Uri class, the corresponding Validator is missing. Here’s a validator I wrote some time ago:

<?php
/**
 * Scienta Zend Additions
 *
 * @category   Scienta
 * @package    Scienta_Validate
 * @copyright  Copyright (c) 2008-2009 Joakim Nygård (http://jokke.dk)
 * @version    $Id$
 */

/** Zend_Validate_Abstract */
require_once 'Zend/Validate/Abstract.php';

/** Zend_Uri */
require_once 'Zend/Uri.php';

/**
 * @category   Scienta
 * @package    Scienta_Validate
 * @copyright  Copyright (c) 2008-2009 Joakim Nygård (http://jokke.dk)
 */
class Scienta_Validate_Uri extends Zend_Validate_Abstract
{
    const INVALID = 'uriInvalid';

    protected $_messageTemplates = array(
        self::INVALID => "'%value%' is not a valid uri",
    );

    public function isValid($value)
    {
        $this->_setValue($value);
    
        $valid = Zend_Uri::check($value);
    
        if ($valid) {
            return true;
        } else {
            $this->_error(self::INVALID);
            return false;
        }
    }
}

Save the above to the file library/Scienta/Validate/Uri.php with library being the directory with the Zend framework. It can then be used on a form element as follows:

$element->addValidator(new Scienta_Validate_Uri());