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
3
  • 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. Commented Dec 14, 2011 at 13:37
  • This might be useful: stackoverflow.com/questions/161738/… Commented Dec 14, 2011 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."); Commented Dec 14, 2011 at 14:17

4 Answers 4

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");
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

1 Comment

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.
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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.