简体   繁体   中英

Laravel validate url name and protocol

I need validate url. I need allow only main url sites, example:

http://example.com
https://example.com

I need prevent these urls on my site:

http://example.com/page/blahblahblah
https://example.com/other/bloa

I use regex:

'url' => ['required', 'url', 'regex:/((http:|https:)\/\/)[^\/]+/']

When user insert url, he can insert http://example.com/page/blahblahblah why? My regex is not working.. Validation is passing

You can use the following pattern to ensure a URL does not contain subdirectories:

^(?:\S+:\/\/)?[^\/]+\/?$

Explanation:

^ asserts position at start of the string

Non-capturing group (?:\\S+://)?

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

\\S+ matches any non-whitespace character (equal to [^\\r\\n\\t\\f\\v ])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

: matches the character : literally (case sensitive)

/ matches the character / literally (case sensitive)

/ matches the character / literally (case sensitive)

Match a single character not present in the list below [^/]+

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

/ matches the character / literally (case sensitive)

/? matches the character / literally (case sensitive)

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

You could write a custom validator and use a combination of filter_var and parse_url?

Something as follows will do the job...

<?php

$url = "http://example.com/page/blahblahblah";

if (!filter_var($url, FILTER_VALIDATE_URL)) {
    return false;
}

$parts = parse_url($url);

echo "{$parts['scheme']}://{$parts['host']}";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM