So I am trying to use Laminas\Validator\Uri package to validate a URL. Here is a code snippet:
$uriValidator = new Uri();
$result = $uriValidator->isValid($someVariable);
Regardless of $someVariable value, even if it is just one letter, expression evaluates to true. I tried to set a Scheme for UriHandler but it did not change anything.
$uriValidator->getUriHandler()->setScheme('http');
My aim is to configure $uriValidator so that it validates a standard URL, just like filter_var($url, FILTER_VALIDATE_URL) does.
Any advice will be appreciated.
I 've tested this behaviour of the Laminas Uri validator today and the described behaviour could be reproduced. Although this behaviour feels like a mistake, it is not.
As so often, it is a matter of configuration. When you initialize the validator without any further options it allows relative and absolute uri 's at the same time. With this in mind the given string could be a relative url. The validator validates the string as a typical uri, since blah! is a valid path.
The following example validates an URL (which is indeed something different than an URI) when it comes to the technical definition.
<?php
declare(strict_types=1);
namespace Marcel;
use Laminas\Validator\Uri;
$validator = new Uri([
'allowAbsolute' => true,
'allowRelative' => false,
]);
$validator->isValid('blah!'); // results into false
If the laminas/laminas-uri
standard handlers do not fit your needs, you can even write your own uri handler and use it with the validator. You own uri handler has to extend from \Laminas\Uri\Uri
and can be used like this:
<?php
declare(strict_types=1);
namespace Marcel;
use Laminas\Validator\Uri;
use Marcel\Uri\MyOwnHandler;
$validator = new Uri([
'uriHandler' => MyOwnHandler::class,
'allowAbsolute' => true,
'allowRelative' => false,
]);
$validator->isValid('blah!'); // results into false
Instead of reinventing the wheel, you can use alternatives like league/uri
and implement this in your own uri handler to validate urls.