The Web Blinders logo

Programming

HTML-Javascript How to validate a Url or link field ?

Collecting Website Address of a person or a company is very common.We have to validate urls to make sure we can reach them on those addresses.
HTML-Javascript How to validate a Url or link field?
Validating a url field

JAVASCRIPT REGULAR EXPRESSION FOR VALIDATING URLS

isValidUrl(url) returns true if url is a valid url and please note that ip addresses,urls with our protocols are considered as invalid


/*

Returns true if url is valid 
ip addresses,urls with out http/https are invalid
see below examples to know more

*/
function isValidUrl(url) {
  let validUrl = /^(?:(?: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;
  return validUrl.test(url);
}
console.log(isValidUrl(""));                   // false
console.log(isValidUrl("htt://www.fb.com"));   // false
console.log(isValidUrl("http://www.fb.com"));  // true
console.log(isValidUrl("https://www.fb.com")); // true
console.log(isValidUrl("http://127.0.0.1"));   // false
console.log(isValidUrl("192.168.0.1"));        // false
console.log(isValidUrl("192.168.0.1"));        // false
console.log(isValidUrl("106.0.36.99"));        // false

Live demo of Url Validation function used with an HTML Form input - https://www.thewebblinders.in/demos/javscript-html-url-validation.html

Use comments section for any queries.

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES