intro
Let’s create simple url validator. You can download the source code of this article from here.
1.Create Validate Class
Create the file
library/My/Validate/SimpleUrl.php
with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?php require_once 'Zend/Validate/Abstract.php'; require_once 'Zend/Validate/Hostname.php'; class My_Validate_SimpleUrl extends Zend_Validate_Abstract { const MSG_INVALID_URL = 'notValidUrl'; const MSG_INVALID_HOSTNAME = 'notValidHostname'; const PATTERN_URL = '/^(https?:\\/\\/)?([^:\\/]+)(:[1-9][0-9]{0,4})?(\\/.*)?$/'; const SUBPATTERN_HOSTNAME_INDEX = 2; protected $_messageVariables = array( 'hostname' => '_hostname' ); protected $_messageTemplates = array( self::MSG_INVALID_URL => "'%value%' is not a valid url", self::MSG_INVALID_HOSTNAME => "'%hostname%' is not a valid hostname" ); protected $_hostname = ''; public function isValid($value) { $this->_setValue($value); $valueString = (string) $value; $status = @preg_match(self::PATTERN_URL, $valueString, $matches); if (!$status) { $this->_error(self::MSG_INVALID_URL); return false; } $hostname = $matches[self::SUBPATTERN_HOSTNAME_INDEX]; $this->_hostname = $hostname; $option = Zend_Validate_Hostname::ALLOW_DNS | Zend_Validate_Hostname::ALLOW_IP; $hostname_validate = new Zend_Validate_Hostname($option); $status = $hostname_validate->isValid($hostname); if (!$status) { $this->_error(self::MSG_INVALID_HOSTNAME); return false; } return true; } } |
2.Add Validator
Add the simple url validator to form object like the following.
You can add your validators to element objects like the following.
1 2 3 4 5 6 7 8 9 10 11 |
$form = new Zend_Form(); $form->addElementPrefixPath('My_Validate', 'My/Validate/', Zend_Form_Element::VALIDATE) ->setAction($this->_request->getBaseUrl() . '/index/profile') ->setMethod('post'); //... $url = $form->createElement('text', 'url'); $url->setLabel('URL') //... ->addValidator('simpleUrl', false); //... |
You can add your validators to element objects like the following.
1 2 |
$url->addPrefixPath('My_Validate', 'My/Validate/', Zend_Form_Element::VALIDATE) |
3.Check
Let’s access your web server and check the url validation.
I prefer to not use PrefixPath for the validators, I am using class instances instead.
Thank you for your suggestion.
Excellent Idea,