5

I want to validate urls. It should accept:

http://google.com

http://www.google.com

www.google.com

google.com

I refer Regex to match URL .

But it is not supporting google.com .

Community
  • 1
  • 1
discky
  • 14,859
  • 8
  • 20
  • 11
  • You've pointed to a question with several answers. Which regex are *you* using? – Greg Hewgill Dec 28 '11 at 19:16
  • @discky- I think that your answer lies between both what Tom van der Woerdt and I have recommended. Tom's suggestion will prepend "http" if it is missing and my suggestion validate's the rest of the url. The only problem is that if you need "https" or "ftp" then the user needs to specify that so it may be best to validate against them entering the proper prefix to begin with. – Matt Cashatt Dec 28 '11 at 19:25
  • You are using jQuery, and jQuery has URL validation regex routines IIRC – fge Dec 28 '11 at 19:33

4 Answers4

3

Simply prepend http:// if it's not there and then test.

if (inputURL.substring(0,7) != 'http://' && inputURL.substring(0,8) != 'https://') {
    inputURL = 'http://' + inputURL;
}

No large libraries required or anything, just a few lines of code.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
0

This is a better way I think should be used to validate urls

reg = /https?:\/\/w{0,3}\w*?\.(\w*?\.)?\w{2,3}\S*|www\.(\w*?\.)?\w*?\.\w{2,3}\S*|(\w*?\.)?\w*?\.\w{2,3}[\/\?]\S*/
reg.test('www.google.com')    # will return true
reg.test('www.google')        # will return false

Let me know if you still not getting it correct.

Pradeep Agrawal
  • 307
  • 2
  • 10
0

This simple helper method uses Regex to validate URLs and will pass on each of your test cases. It also takes into account for whitespace so google.com/a white space/ will fail.

    public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
    {
        value = value.Trim();
        if (required == false && value == "") return true;
        if (required && value == "") return false;

        Regex pattern = new Regex(@"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$");
        Match match = pattern.Match(value);
        if (match.Success == false) return false;
        return true;
    }
Andrew Reese
  • 854
  • 1
  • 11
  • 27
0
function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}
Matt Cashatt
  • 23,490
  • 28
  • 78
  • 111