There is a simple way to validate if an URL is valid in Javascript, no messy Regex needed.
const url = new URL(url [, base])
base
is only required if you enter a relativeURL
.
The only catch here is that... IE does not support this. If IE support is NOT required, e.g. building an admin tool for the internal team or it will be launched under a browser instance, etc., use this!
You can use it as a standalone test:
export const isValidUrl = (url) => {
try {
new URL(url);
} catch (e) {
console.error(e);
return false;
}
return true;
};
And you can integrate with a Yup schema:
const schema = yup.object().shape({
url: yup
.string()
.test("is-url-valid", "URL is not valid", (value) => {
return isValidUrl(value);
})
});
Top comments (2)
It not 100% correct
isValidUrl failed for pattern {string}:
isValidUrl("asda:") //true
Pretty code, thanks!