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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With