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:
exportconstisValidUrl=(url)=>{try{newURL(url);}catch(e){console.error(e);returnfalse;}returntrue;};
And you can integrate with a Yup schema:
constschema=yup.object().shape({url:yup.string().test("is-url-valid","URL is not valid",(value)=>{returnisValidUrl(value);})});
Top comments(2)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse