Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lucasvrm's avatar

URL validation

I am using the url validation built in laravel and PHP (filter_var/FILTER_VALIDATE_URL) but this does not work like I expected.

URL's such as bellow are validated: hp://example.com htt://example.com htts://example.com

So... What is the best way to validate an URL? I am building a URL Shortener for learning purposes and this issue came up.

I am doing step by step and trying to learn the most I can if every one.

Does anyone knows a better way to validate an URL then the filter_var/FILTER_VALIDATE_URL?

I am using Laravel 5.1.10

0 likes
7 replies
bobbybouwmann's avatar

The best way is a regular expression. My regex just checks for http and https, you can adjust the regex and add the ftp one as well.

lucasvrm's avatar

Ok @bobbybouwmann. But how do I use the regex... The expression I want to use is:

_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:.\d{1,3}){3})(?!(?:169.254|192.168)(?:.\d{1,3}){2})(?!172.(?:1[6-9]|2\d|3[0-1])(?:.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]-)[a-z\x{00a1}-\x{ffff}0-9]+)(?:.(?:[a-z\x{00a1}-\x{ffff}0-9]-)[a-z\x{00a1}-\x{ffff}0-9]+)(?:.(?:[a-z\x{00a1}-\x{ffff}]{2,})).?)(?::\d{2,5})?(?:[/?#]\S)?$_iuS

Do I have to create a Service Provider? What is the best option?

bobbybouwmann's avatar

You can just pass it in the rules

$regex = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';

return [
    'url' => 'regex:' . $regex,
];
1 like
lucasvrm's avatar

I managed to do what you told me. Thanks @bobbybouwmann

I passed my regex into the rules. I had to create an array to do that.

$regex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:.\d{1,3}){3})(?!(?:169.254|192.168)(?:.\d{1,3}){2})(?!172.(?:1[6-9]|2\d|3[0-1])(?:.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]-)[a-z\x{00a1}-\x{ffff}0-9]+)(?:.(?:[a-z\x{00a1}-\x{ffff}0-9]-)[a-z\x{00a1}-\x{ffff}0-9]+)(?:.(?:[a-z\x{00a1}-\x{ffff}]{2,})).?)(?::\d{2,5})?(?:[/?#]\S)?$_iuS';

        $rules = array('hewit' => array('required', 'regex:'.$regex));

        $messages = [
            'hewit.required' => 'enter the url you want to hew',
            'hewit.regex' => 'your url have to be a valid url' . "<br/>" . "<span class='val_error_small'>". '(try putting http:// or https:// or another prefix at the beginning)'. "</span>",
        ];
bobbybouwmann's avatar

Yeah, because of the '|' ;) Well glad you managed to get the perfect url ;)

Please or to participate in this conversation.