Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Valid URL Regular Expression
var isValidUrl = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[​6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1​,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00​a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u​00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;
var url = "...";
console.log(isValidUrl.test(url)) //=> true/false
@strongant

This comment has been minimized.

Show comment
Hide comment
@strongant

strongant Mar 7, 2017

var url = "https://wwwww.google.com";

console.log(isValidUrl.test(url)) //=> true/false
VM1063:5 true

It is wrong.Do you think it?

var url = "https://wwwww.google.com";

console.log(isValidUrl.test(url)) //=> true/false
VM1063:5 true

It is wrong.Do you think it?

@evanfoster

This comment has been minimized.

Show comment
Hide comment
@evanfoster

evanfoster Jun 8, 2018

@strongant
https://wwwww.google.com is a valid URL. www has no special meaning. It's just a subdomain of google.com, same as images.google.com or shopping.google.com. What you need to do is extract the host from the URL and then do some sort of validation there. Maybe try a DNS lookup for that host (although that's probably a terrible idea.)

Alternatively, don't validate to that level. Be conservative in what you send, be liberal in what you accept.

evanfoster commented Jun 8, 2018

@strongant
https://wwwww.google.com is a valid URL. www has no special meaning. It's just a subdomain of google.com, same as images.google.com or shopping.google.com. What you need to do is extract the host from the URL and then do some sort of validation there. Maybe try a DNS lookup for that host (although that's probably a terrible idea.)

Alternatively, don't validate to that level. Be conservative in what you send, be liberal in what you accept.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment