Skip to Content
Course content

154: Common Regex Patterns for Validation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're a bouncer at a high-end club. You aren't reading the guest's entire life story to decide if they can enter; you're just checking for a few specific markers. "Do you have an ID? Is it expired? Are you wearing a collared shirt?" If they hit all those marks, they're in. If they miss even one, they're turned away.

Validation regex works exactly like that bouncer. Your input string is the guest, and your regex pattern is the checklist. We aren't usually trying to "parse" the data here—we just want a boolean true or false to decide if the data is clean enough to let into our database.

Taming the Email Beast

I'll be honest with you: trying to write a "perfect" email regex that covers every single edge case in the official RFC specifications is a waste of your time. You'll end up with a 500-character monster that is impossible to maintain. In the real world, we use a "good enough" pattern that catches 99% of typos while letting valid emails through.

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

Here is the logic: we ensure there are no spaces or @ symbols at the start, followed by a mandatory @, then more non-space/non-@ characters, a literal dot, and finally a domain suffix. It's lean, it's fast, and it doesn't break your brain when you have to read it six months from now.

Enforcing Password Rigor with Lookaheads

Passwords are different. We aren't looking for a specific sequence; we're looking for the presence of certain characters anywhere in the string. This is where "positive lookaheads" (?=...) come in. Think of this as the bouncer saying, "I don't care where it is in your wallet, but you must have a photo ID."

const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;

I use this pattern constantly. It checks for three things without "consuming" the string: at least one lowercase letter, one uppercase letter, and one digit. Only after those three checks pass does it actually validate that the total length is at least 8 characters. If any of those lookaheads fail, the whole thing returns false immediately.

Handling the Chaos of Phone Numbers

Users are unpredictable. Some write phone numbers as (123) 456-7890, others as 123-456-7890, and some just smash the numbers together. If you're too strict, you'll frustrate your users. The goal here is to be flexible with the separators but strict about the digit count.

const phoneRegex = /^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;

Notice how I used \? and [-.\s]?. This tells JavaScript that the parentheses and the dashes/dots/spaces are optional. We're essentially saying, "I'm looking for 10 digits, and I'll tolerate some common punctuation in between them."

Knowing When to Stop

Here is a piece of advice from someone who has spent too many hours staring at backslashes: if your regex starts looking like a cat walked across your keyboard and you can't explain what it does to a junior dev in thirty seconds, stop. You're over-engineering. In those cases, I usually break the validation into three or four simple .includes() or .length checks. Readability always wins over "cleverness" in a production codebase.




📋 Practical Task

Building a User Account Validation Suite

You are tasked with creating a validation module for a new user registration page. Instead of a single function, create a Validator object that contains the regex patterns we discussed today.

Requirements:

  • Create an object named Validator with three methods: validateEmail(email), validatePassword(password), and validatePhone(phone).
  • Each method should return true if the input matches the pattern and false otherwise.
  • The validatePassword method must enforce the "rigor" rules: at least one uppercase, one lowercase, one number, and minimum 8 characters.
  • Test your object with a "dirty" dataset (e.g., an email without a dot, a password that is too short, and a phone number with too many digits) to ensure your bouncer is doing its job correctly.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.