Validating URLs with Zend Framework

with one comment

It’s pretty common to want to validate a URL when processing a form. The Zend Framework has a lot of validators that can be used out of the box with Zend_Form. Unfortunately, there is no Zend_Validate_Uri. Upon closer inspection, you will find Zend_Uri, which indeed can be used to check for a valid URL; however, it does not implement the Zend_Validate_Interface and cannot be used as a drop-in form element validator. Fortunately, it is pretty easy to come up with something that can be dropped in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Url_Validator extends Zend_Validate_Abstract
{
    const INVALID_URL = 'invalidUrl';
 
    protected $_messageTemplates = array(
        self::INVALID_URL   => "'%value%' is not a valid URL.",
    );
 
    public function isValid($value)
    {
        $valueString = (string) $value;
        $this->_setValue($valueString);
 
        if (!Zend_Uri::check($value)) {
            $this->_error(self::INVALID_URL);
            return false;
        }
        return true;
    }
}
 
// When creating the form:
$website = $form->createElement('text', 'website');
$website->addValidator(new Url_Validator);

This reminds me of a senior coder I used to work under who constantly yelled at us to “Code to the interface!”. ;)

Note: I originally posted this as a response to a thread here.

Written by steve

February 9th, 2009 at 9:10 pm

Posted in PHP, code, zend framework