DEV Community

loading...

Simple URL validation with Javascript

calvinpak profile image CP Updated on ・1 min read

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 relative URL.

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;
};
Enter fullscreen mode Exit fullscreen mode

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);
    })
});
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide