by gregsadetsky · 5y ago · 0 comments
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 have its own problems)
What's a good solution? I both want to validate URLs, but also let users enter "example.com". But if I simply do
if(validateURL(url)) {
return true;
} else if(validateURL("http://" + url)) {
return true;
} else {
return false;
}
i.e. validate the given URL, and as a fallback, try to validate "http://" + the given url, that opens the door to weird, non-URLs strings being incorrectly validated...Help :-)
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? const parseUrl = url => validateUrl(url) ? url : null;
return parseUrl(url) || parseUrl('http://'+url) || null;I'd probably do the same for poorly formatted URLs. When the user hits Submit, a prompt appears saying, "Did you mean `https://example.com`?"
if it's really important, you could try making a request to the url and see if it loads, but that still doesn't validate its the url they intended to input.
might be cool to load the url with puppeteer and capture a screenshot of the page. if they can't recognize their own website, it's on them.