Validating input: emails, URLs and addresses

Intermediate · 8 min

What a regex can check about an email, URL or IPv4 address (shape), what it cannot (that it exists), and when the platform's own parser beats a pattern.

Before thisAlternationCounted repetitionAnchors and line boundariesCharacter classesCatastrophic backtracking and ReDoS

CodeOpinion · 8 min

Validating input: emails, URLs and addresses

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodeOpinionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A regex can check the shape of an email address. It cannot tell you the mailbox exists. The only reliable check is to send a message and see if the person clicks.
  • A short shape check like ^[^\s@]+@[^\s@]+\.[^\s@]+$ rejects obvious junk, accepts nonexistent domains, and also rejects a@localhost. Decide what you want, then test both valid and invalid inputs.
  • The HTML standard calls its own email pattern a willful violation of RFC 5322. It rejects non-ASCII addresses and accepts a@b. Copying it means copying those choices.
  • For URLs and IP addresses, prefer the parser the platform gives you: new URL, URL.canParse, net.isIPv4, Python's ipaddress. They reject http://999.1.1.1, which a naive pattern accepts.
  • If you must use a regex for IPv4, each octet is (?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d). Anchor it, and remember Python's $ matches before a trailing newline, so use fullmatch.

The check you can and cannot do

A signup form needs an email address. Your first idea is a regex, because the field is text and the question is “does this look right?”. That question has a good regex answer. But the question the business cares about is “can I reach this person?”, and no pattern can answer it. The characters ada@nonexistent-domain-xyz.invalid form a perfectly well-shaped address, and my shape check accepted it:

const shape = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
shape.test("ada@nonexistent-domain-xyz.invalid")   // true

Existence lives in DNS and mail servers. The only check that works is to send a message with a link and see whether it is clicked. So use the regex for what it is good at: catching typos and obvious junk before you spend a network call.

A small shape check, and its choices

That pattern says: one or more characters that are neither whitespace nor @, an @, more such characters, a dot, more of them. I ran it on Node 26 against 18 inputs. It accepted ada@example.com, user+tag@example.co.uk, and the non-ASCII ünï@example.com. It rejected a b@example.com, @example.com, a@@example.com, ada@example and a@localhost. It also accepted ada@example..com and ada@-bad.com, which are not valid domains.

Every one of those is a decision. Rejecting a@localhost is right for a public signup and wrong for an internal tool. Accepting ada@example..com is sloppy but harmless if you send a confirmation anyway. A short pattern that is honest about being a shape check is better than a long one pretending to be a validator.

The email regex rabbit hole

The long patterns come from RFC 5322, which allows quoted local parts like "quoted space"@example.com, comments and more. My shape check and the HTML standard’s pattern both rejected that quoted address. The HTML standard says its email pattern is “a willful violation of RFC 5322”, which it calls “simultaneously too strict (before the ‘@’ character), too vague (after the ‘@’ character), and too lax” to be of practical use. Its regex is:

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

I ran it on the same inputs. It rejects ünï@example.com and ada@exämple.com (it is ASCII only), rejects ada@-bad.com and ada@example..com, and accepts a@b, a@localhost and ada.@example.com. So it is stricter than my pattern about domains, laxer about dots, and wrong for internationalised addresses. There is no pattern that is correct for everyone. This is where the lesson stops being about regex and starts being about what you want.

Use the platform’s parser when there is one

For URLs the grammar is intricate enough that a pattern is the wrong tool. I compared a naive ^https?:\/\/\S+$ with new URL:

"http://"                naive false   URL throws
"https://."              naive true    URL parses, host "."
"https://example.com:99999"  naive true  URL throws
"http://999.1.1.1"       naive true    URL throws
"https://例え.jp"         naive true    URL parses, host xn--r8jz45g.jp
"javascript:alert(1)"    naive false   URL parses, protocol javascript:

The parser rejected the bad port and the impossible address, and converted the Japanese domain to its ASCII form. The last line is the trap: new URL accepts javascript: URLs, so after parsing, check url.protocol against an allowlist like ["https:", "http:"]. URL.canParse(u) gives a boolean without a try/catch. Python has urllib.parse and ipaddress, which on my machine raised “Octet 256 (> 255) not permitted” for 256.1.1.1.

IPv4 octets

When you do need a regex, build it from the octet. Digits 0 to 255 need four alternatives:

(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)

That is 250-255, 200-249, 100-199, and 0-99 without a leading zero. Joined with \. three times and anchored, the full pattern is 81 characters. Against the loose \d{1,3} version, it rejected 256.1.1.1 and 999.999.999.999, which the loose one accepted, and it agreed with net.isIPv4 on every one of the 12 inputs I tried. It also rejected 01.02.03.04, which is deliberate: leading zeros are ambiguous (some tools read them as octal), and Python’s ipaddress also refused them.

Do not reach for [0-12] to mean “0 to 12”. A class is a set of characters, so [0-12] is 0, 1, 2, 1, 2. I tested it: it matched 2 and 1 and not 12.

Anchors decide whether validation works

A validator without ^ and $ accepts any string that merely contains a good one. And in Python, $ has a subtle habit: re.match(r'^\d+$', '12\n') matched, while re.fullmatch(r'\d+', '12\n') and ^\d+\Z did not. JavaScript’s ^\d+$ rejected "12\n". For validation in Python, fullmatch is the safe choice.

About the video

“Regex for Email Validation? Think Again!” by CodeOpinion was published 2 April 2025 and runs 7 minutes 42 seconds. The description argues that a valid-looking email address does not mean the mailbox exists, and promises the common mistakes and the right way. The chapters are “Problem”, “Valid Email Address”, “Test Email” and “Mailbox Validation”. I couldn’t read a transcript, so I can’t say which language its examples use or whether it shows a regex at all. It does not cover URLs or IP addresses, which this lesson adds. English per its title and description.

What I did not run

Sending a real confirmation email, IDN or punycode edge cases beyond the one URL, IPv6 patterns, and email validation libraries. The RFC 5322 grammar itself I only know through the HTML standard’s description of it.

Next

Numbers and dates have the same pattern, shape yes and meaning no: dates, times and numbers.

Check yourself

  1. 01Why can't a regex prove an email address is valid?

    Validity means a mailbox exists and the person owns it. That depends on DNS and a mail server, not on the characters. A regex can only check the string's shape. Send a confirmation message for the real test.

  2. 02What is wrong with /^\d{1,3}(\.\d{1,3}){3}$/ as an IPv4 check?

    It accepts 999.999.999.999, because three digits can be any number up to 999. Each octet needs the ranges 25[0-5], 2[0-4]\d, 1\d\d and [1-9]?\d, or you can call net.isIPv4 instead.

  3. 03Why use new URL(...) instead of a regex to check a URL, and what must you still check yourself?

    The parser applies the real URL grammar: it rejected http://999.1.1.1 and https://example.com:99999, which my naive regex accepted. But new URL('javascript:alert(1)') succeeds, so you still check the protocol against an allowlist.

  4. 04In Python, why can re.match(r'^\d+$', '12\n') succeed?

    Python's $ matches at the end of the string and also just before a final newline. Use re.fullmatch(r'\d+', s), or \Z instead of $. JavaScript's $ does not do this.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark