
How I Validated for Specific URLs in JavaScript
In a pet project that I worked on recently, one of the requirements was to allow users to submit the URL to their Facebook social media profile. This article describes how I ensured that only Facebook profile URLs were submitted. JavaScript was used but it does not matter as much as the algorithm used; and that algorithm is described here. function validateUrl(url, expectedOrigin) { const urlObject = new URL(url); const originPattern = new RegExp(expectedOrigin.toLowerCase() + "$"); const isValid = urlObject.origin.toLowerCase().match(originPattern); if (!isValid) { throw new Error("Invalid URL"); } return `${urlObject.origin}${urlObject.pathname}`; } console.log(validateUrl("https://facebook.com/hi-there", "facebook.com")); //https://facebook.com/hi-there console.log(validateUrl("https://handbook.com/hi-there", "facebook.com")); // throws error Components of a URL. Source - MDN ...