JavaScript Regular Expression to Validate Url

JS Regex url validation

I change the function to Match + make a change here with the slashes and its work: (http(s)?://.)

The fixed function:

function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}

Regular expression for URL validation (in JavaScript)

The actual URL syntax is pretty complicated and not easy to represent in regex. Most of the simple-looking regexes out there will give many false negatives as well as false positives. See for amusement these efforts but even the end result is not good.

Plus these days you would generally want to allow IRI as well as old-school URI, so we can link to valid addresses like:

http://en.wikipedia.org/wiki/Þ
http://例え.テスト/

I would go only for simple checks: does it start with a known-good method: name? Is it free of spaces and double-quotes? If so then hell, it's probably good enough.

Regex for website or url validation

Use the regex ^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$

This is a basic one I build just now. A google search can give you more.

Here

  • ^ Should start with
  • ((https?|ftp|smtp)://)? may or maynot contain any of these protocols
  • (www.)? may or may not have www.
  • [a-z0-9]+(.[a-z]+) url and domain and also subdomain if any upto 2 levels
  • (/[a-zA-Z0-9#]+/?)*/? can contain path to files but not necessary. last may contain a /
  • $ should end there

var a=["http://www.sample.com","https://www.sample.com/","https://www.sample.com#","http://www.sample.com/xyz","http://www.sample.com/#xyz","www.sample.com","www.sample.com/xyz/#/xyz","sample.com","sample.com?name=foo","http://www.sample.com#xyz","http://www.sample.c"];var re=/^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/;a.map(x=>console.log(x+" => "+re.test(x)));

Check if a JavaScript string is a URL

A related question with an answer

Or this Regexp from Devshed:

function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}


Related Topics



Leave a reply



Submit