5 ms·
The utility mentioned isn't the approach I would recommend for 'validating absolute URLs' -- for that I would simply use try..catch with the URL() constructor a
by Sephr 3y ago
The utility mentioned isn't the approach I would recommend for 'validating absolute URLs' -- for that I would simply use try..catch with the URL() constructor and no base URL.
My linked utility is specifically for validating that a URL is valid (won't throw an error when passed to the URL constructor) and doesn't need additional encoding. This helps with my use case which is a 'create URL classification' UI that allows users to input URL matchers in a multitude of formats.
For additional context, some inputs are invalid even with a base URL. e.g. new URL('//:0', 'https://- https://-') will throw an error.
Your first critique doesn't seem relevant as this is mostly for checking if a URL is 'valid' (i.e. doesn't throw an error when used).
Also, for your second critique, the username + password is actually part of the origin as used by both of my snippets. For example, isValidURL('https://a:b@c.d/ https://a:b@c.d/') and isValidURL('https://a:b@[::1]/ https://a:b@[::1]/') both return true for me.
Do you have a URL that gave a bad result? If so, feel free to mention it here and in the comments for the gist so that users of my snippet can be made aware of its limitation.