Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL regex validation

i made that:

 /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}

and checked it with a validator but on my page it is not working:

var re = /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1};
if (!re.test(url)) { 
    alert("url error");
    return false;
}

i get this error

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Timestamp: Tue, 30 Nov 2010 14:23:10 UTC


Message: Expected ')' in regular expression
Line: 781
Char: 23
Code: 0
URI: http://*************************
like image 544
Y.G.J Avatar asked Nov 30 '10 14:11

Y.G.J


People also ask

What is a URL regular expression?

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string. Discover UI Bakery – an intuitive visual internal tools builder.

What is a validated URL?

Link validation pings the destination of a URL and tests for errors. This helps avoid broken and invalid links in your published document, and is especially useful for bloggers.

How validate URL in PHP regex?

Use the filter_var() function to validate whether a string is URL or not: var_dump(filter_var('example.com', FILTER_VALIDATE_URL));


1 Answers

I will post, although the question has been accepted.

That regex is still incomplete.

http://www.-1-.de is not a valid domain name but would pass your test.

Here's what I use:

~^
(?:ht|f)tps?://

(?:[a-z0-9] (?:[a-z0-9-]*[a-z0-9])?      \.)*

(?:[a-z0-9][a-z0-9-]{0,62}[a-z0-9])
(?:\.[a-z]{2,5}){1,2}

$~ix

Covers http(s), ftp(s) and .co.uk TLDs and the like. Also covers subdomains which can be 1 character in length (m.example.com for mobile versions of webpages) but will not allow m-.example.com.

Surely some might object as to the regex's completeness, since .pro TLDs require at least 4 characters as a domain name. ;-)

Also IDN domain names will only pass my regex after conversion (i.e. in the "xn--" format).

like image 97
Linus Kleen Avatar answered Oct 06 '22 00:10

Linus Kleen