Re:In search of the perfect URL validation regex (2010)
by anderskaseorg on Saturday September 25, 2021 @03:54PM
(#28655756)
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.
[ Parent
| on HN ]
Re:In search of the perfect URL validation regex (2010)
by JadeNB on Saturday September 25, 2021 @05:31PM
(#28656374)
I know we're not golfing, but it pains me to see that repetition in the middle. Mightn't we write
if (!validateURL(url)) {
url = "http://" + url;
if (!validateURL(url)) {
url = null;
}
}
return url;
to snip a small probability of a bug?
Re:In search of the perfect URL validation regex (2010)
by wolfgang42 on Saturday September 25, 2021 @05:43PM
(#28656466)
I find that branchiness (and mutation of the variable) harder to follow. Personally, I’d just take “parse, don’t validate” to its logical conclusion and go for:
const parseUrl = url => validateUrl(url) ? url : null;
return parseUrl(url) || parseUrl('http://'+url) || null;