DEV Community

CP
CP

Posted on • Updated on

Simple URL validation with Javascript

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

Top comments (2)

Collapse
 
prafulladeshmukh profile image
Prafulla Deshmukh

It not 100% correct

isValidUrl failed for pattern {string}:
isValidUrl("asda:") //true

Collapse
 
sunzhuoshi profile image
sunzhuoshi

Pretty code, thanks!