2

Can anyone tell the regular expression for URL validation in JavaScript?

I need to validate for http/https://example.com/...

I tried using

((^http/://[a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?

The examples that i tried to check were:

http://google.com
https://google.com
www.google.com
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Poppy
  • 2,902
  • 14
  • 51
  • 75
  • 2
    What would be an example of a few valid urls? The url you provided above is not valid and if i check the regex pattern it looks like there a re a few problems in there. – Patrick Dec 14 '11 at 13:37
  • This might be useful: http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url – Mahmoud Gamal Dec 14 '11 at 13:37
  • This worked : $.validator.addMethod("refurl", function(value, element) { var urlregex = new RegExp("^(http:\/\/.|https:\/\/.|ftp:\/\/.|www.){1}([0-9A-Za-z]+.)"); return value == '' ? true: urlregex.test(value); }, "One or more values in the Link field(s) are not valid URL."); – Poppy Dec 14 '11 at 14:17

4 Answers4

1

You could try something like this:

var url = "Some url..."; 
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/

if (regexp.test(url)) {
    alert("Match");
} else {
    alert("No match");
}
José
  • 391
  • 3
  • 14
0

Try:

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)\
                  (:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

if (isUrl("your_url_here")) {
    console.log("URL is valid");
} else {
    console.log("URL is invalid");
}

via: http://snippets.dzone.com/posts/show/452

miku
  • 181,842
  • 47
  • 306
  • 310
0

A much more simplified version could be: ^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(/\S*)?$ I don't know if this is sufficient for you though, as I don't know what you want to do with the results.

Pieter
  • 3,339
  • 5
  • 30
  • 63
  • Well, those aren't commonly used where I come from, so I didn't think of them while writing the regex. But it's an easy fix to allow for those as well. And longer tld's are possible also. Just increase the maximum size for the tld-part. – Pieter Dec 14 '11 at 13:49
0

Maybe you could just:

s,(https?://)(?!www\.),\1www.,

and use jquery to validate the transformed string?

It would avoid the job of writing yet another regex to match an URL...

fge
  • 119,121
  • 33
  • 254
  • 329