Skip to content

Instantly share code, notes, and snippets.

@davidhartsough
Last active June 21, 2024 23:31
Show Gist options
  • Save davidhartsough/a125b5cef0721880e034e16b8899b842 to your computer and use it in GitHub Desktop.
Save davidhartsough/a125b5cef0721880e034e16b8899b842 to your computer and use it in GitHub Desktop.
URL validator RegEx: code for JS and the HTML URL input pattern attribute to validate if the entry is a valid URL

My favorite URL RegEx

I spent way too long trying to dial this in, so I had to document my results and share them.

Check out the end result on RegExr: https://regexr.com/7fjmt

This RegEx is intended to accept nearly every valid URL, with a few exceptions; it intentionally excludes:

  • IP addresses
  • networks ranges, database/server addresses, ports
  • any transfer protocol that isn't hypertext
  • any characters that aren't standard latin a-z (A-Z) or 0-9
    • (which means unicode symbols, like "Dingbats", and other language characters are not accepted)
  • http://localhost/
  • data:text/plain;charset=utf-8,OHAI
  • tel:+1234567890

JavaScript

const urlPattern =
  /^(https?:\/\/)((?!-)(?!.*--)[a-zA-Z\-0-9]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}(\/[^\s]*)?$/;

Playground Link

HTML

<input
  type="url"
  pattern="^(https?:\/\/)((?!-)(?!.*--)[a-zA-Z\-0-9]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}(\/[^\s]*)?$"
  title="Enter a valid URL"
  required
/>

JSFiddle

These valid URLs should pass:

These invalid URLs should fail:

References/Resources

I borrowed tests from Mathias Bynens' "search of the perfect URL validation regex".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment