I was just struggling with this -- specifically, our users' "UX" expectation that entering "example.com" should work when asked for their website URL. Most URL validation rules/regex/librairies/etc. reject "example.com". However, if you head over to Stripe (for example), in the account settings, when asked for your company's URL, Stripe will accept "example.com", and assume " http:// " as the prefix (which yes, can h…
Parse, don’t validate. If you need a heuristic that accepts non-URL strings as if they were valid URLs, you should convert those non-URL strings to valid URLs so the rest of your code can just deal with valid URLs. if (validateURL(url)) { return url; } else if (validateURL("http://" + url)) { return "http://" + url; } else { return null; }
if (!validateURL(url)) {
url = "http://" + url;
if (!validateURL(url)) {
url = null;
}
}
return url;
to snip a small probability of a bug?