- 2008-04-07 (Mon) 7:00
- Zend_Validate
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.
<?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.
$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.
$url->addPrefixPath('My_Validate', 'My/Validate/', Zend_Form_Element::VALIDATE)
3.Check
Let's access your web server and check the url validation.
Comments:2
- Snowcore 09-04-16 (Thu) 0:06
-
I prefer to not use PrefixPath for the validators, I am using class instances instead.
- oplabo 09-04-21 (Tue) 15:27
-
Thank you for your suggestion.
Trackbacks:0
- Trackback URL for this entry
- http://www.oplabo.com/article/13/trackback
- Listed below are links to weblogs that reference
- Creating Custom Validators from Open Programming Laboratory