Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

CP
CP

Posted on • Edited 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 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;};
Enter fullscreen modeExit fullscreen mode

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

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
sunzhuoshi profile image
sunzhuoshi
  • Joined

Pretty code, thanks!

CollapseExpand
 
prafulladeshmukh profile image
Prafulla Deshmukh
  • Joined

It not 100% correct

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

It feels like every 2 years I have to re-learn everything. Yeah, that's the life of a developer.
  • Location
    Las Vegas, NV
  • Education
    B.Sc. Electrical Engineer & Computer Science
  • Work
    Founder & CEO at Titans Finance
  • Joined

More fromCP

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp