Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Patterns for Text Processing

Validating Input with Regex

Learn how to validate form input with regular expressions the right way, using anchors, clear structure and honest limits, with patterns for usernames, hex colors, dates, IDs and passwords.

Validation answers one yes-or-no question: does this whole string have the shape I expect? Regex is good at shapes, such as "three letters, a dash, four digits", and bad at meaning, such as "is this a real calendar date?" The best validators combine both: a regex checks the shape, ordinary code checks the meaning.

The key difference from searching is that a validator must match the entire string. That means anchors, always.

Anchor everything

Without anchors, /\d{3}/ is happy with "abc123xyz". To validate, wrap the pattern in ^ and $ (or use \A and \z where available). In JavaScript, avoid the m flag in validators: with it, ^ and $ match at every line, so "ok\n<script>" would pass a one-line check.

Node.js Why anchors matter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In some engines $ also matches before a final newline (PCRE, Python's re.match with $, Java). If that matters, use \z, \Z-aware logic, or trim the input first. See flavors and engines.

A toolbox of validators

Here are common shapes, each with the reasoning behind it. Always test both valid and invalid samples.

Node.js Common validators with test cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at isoDate: it accepts 2025-02-31. The regex checks the shape and the month and day ranges, but only code knows February has 28 days. The honest fix is two steps:

Node.js Shape with regex, meaning with code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Passwords: build rules from lookaheads

Lookaheads let you check several independent conditions at the same start position. Each (?=...) asserts something about the whole string without consuming it.

Node.js Password rules with lookahead

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The one-line version is compact, but the list of small checks gives the user useful feedback. Composition rules also have limited security value; length and a breached-password check matter more.

Emails and URLs: be humble

A fully correct email regex is enormous, because the real grammar allows quoted local parts, comments and more. In practice use a pragmatic check and confirm by sending a message:

JavaScript
/^[^\s@]+@[^\s@]+\.[^\s@]+$/

It rejects obvious typos and accepts nearly everything legal. For URLs, parse with new URL() instead of a regex and then check url.protocol. See extracting data patterns for finding addresses inside text, which has different needs.

Validation checklist

  1. Anchor both ends; no m flag.
  2. Prefer small, specific classes over ..
  3. Bound repetition ({2,15}, not +) so input length is limited, which also helps performance.
  4. Check meaning in code.
  5. Validate on the server even if you validate in the browser.
  6. Test valid and invalid samples, including empty strings and strings with trailing newlines.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must a validation regex usually start with ^ and end with $?

    Without anchors, a match anywhere inside the input makes test return true, so garbage around a valid piece would pass.
  2. 2. What is the best way to validate that 2025-02-31 is a real date?

    Regex handles shape well but calendar rules, such as leap years, are clearer and safer in code.
  3. 3. What do the lookaheads in (?=.\d)(?=.[A-Z]).{8,} do?

    Lookaheads assert conditions at the current position without consuming text, so several rules can be combined.
  4. 4. Which email check is recommended for most forms?

    A short pattern catches typos, and sending a confirmation message proves the address works.

Summary

  • Validators must match the whole string: anchors, and no m flag.
  • Use specific classes and bounded repetition to describe a shape tightly.
  • Regex checks shape; code checks meaning (real dates, existing domains).
  • Lookaheads combine independent rules, but separate checks give better error messages.
  • Keep email checks simple and prove the address by sending a message.

Next: Extracting Data with Regex