2

I need an URL validator inside a form. Now I'm using:

$url = new Zend_Form_Element_Text('url');
$url->addValidator(new Zend_Validate_Hostname());

The code above will validate URL's like: www.domain.com but will fail validation for http://www.domain.com.

What validator should I use in order to validate both, with and without protocol URL's.

2
  • You need to validate both? or just domain name is important?
    – Vadyus
    Jan 3, 2013 at 14:29
  • I need that both URL's will pass the validation process. Jan 3, 2013 at 15:04

3 Answers 3

1

This will validate both domain and uri:

$form->addElement ('text', 'url',array(
            'validators' => array (
                    array(
                        'Callback', 
                        true, 
                        ['callback' => function($value) {
                            if (Zend_Uri::check($value)) {
                                $hostnameValidator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS); //do not allow local hostnames, this is the default
                                $uriHttp = Zend_Uri_Http::fromString($value);
                                return $hostnameValidator->isValid($uriHttp->getHost());
                            }
                            return false;
                        }], 
                        'messages' => [Zend_Validate_Callback::INVALID_VALUE => 'Please enter a valid URL']
                    )
                )
            ));
0

You cant do it with Zend_Validate_Hostname. The way you could do it, is to write your own validator that will split sting into 2 parts - and validate them using Zend_Validate_Hostname for hostname and Zend_Validate_InArray for protocol

0

you need to remove the scheme http, or implement a new re-usable validator http://www.rondobley.com/2011/09/24/how-to-validate-a-url-with-a-scheme-and-hostname-in-zend-framework/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.