Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2: How to make Zend\Validator\Hostname accept url strings with and without http:// or https://

I use Zend\Validator\Hostname to validate an input string containing a url. The problem is that it only accepts URLs of type mydomain.com and not with a http:// or https:// protocol prefix. What is the best way to achieve the desired behaviour?

$inputFilter->add($factory->createInput(array(
                'name'     => 'shop_link',
                'required' => false,
                'filters'  => array(
                        array('name' => 'StripTags'),
                        array('name' => 'StringTrim'),
                ),
                'validators' => array(
                        array(
                            'name'    => 'StringLength',
                            'options' => array(
                                'encoding' => 'UTF-8',
                                'min'      => 1,
                                'max'      => 100,
                            ),
                        ),
                        array(
                            'name'    => 'Hostname',
                            'options' => array(
                                'allow'       => \Zend\Validator\Hostname::ALLOW_DNS, // Allow these hostnames
                                'useIdnCheck' => true,  // Check IDN domains
                                'useTldCheck' => true,  // Check TLD elements
                                'ipValidator' => null,  // IP validator to use
                            ),
                        ),
                ),
        )));

Thanks

like image 631
citizen404 Avatar asked Jun 18 '26 15:06

citizen404


1 Answers

I don't have 50 reputation to comment Sam's answer, but Hostname::ALLOW_URI doesn't work. And didn't work year ago - https://stackoverflow.com/a/13902180/822947. And shouldn't work, if you look at the source code. Strange that it has two upvotes.

$validator = new \Zend\Validator\Hostname();
$validator->setAllow($validator::ALLOW_DNS | $validator::ALLOW_URI);
var_dump($validator->isValid('http://domain.com')); // false!
like image 150
yanot Avatar answered Jun 20 '26 05:06

yanot