๐ŸŽ“ 3-WEEK WEB DEV โ†’ VALIDATION MASTERY

๐Ÿ“ Form Validation: From HTML5 to Advanced JavaScript

HTML + CSS + JavaScript โ€” real-time validation, password strength, regex patterns, and professional UX patterns.

โœ… required attribute ๐ŸŽจ :valid / :invalid โšก custom JS ๐Ÿ” password strength ๐Ÿ“ regex patterns ๐Ÿšซ preventDefault
๐Ÿ”ฐ LEVEL 1: HTML5 Built-in Validation

Zero JavaScript needed โ€” browser does the work

<input required>
<input type="email">
<input type="number" min="18" max="99">
<input pattern="[A-Z]{3}" title="3 uppercase letters">
โœ… Pros: Easy, no JS, works instantly.
โŒ Cons: Ugly default popups, weak email check (a@b passes), limited styling.
๐ŸŽจ LEVEL 2: CSS Validation States
input:invalid {
  border: 2px solid red;
  background: #fff5f5;
}
input:valid {
  border: 2px solid green;
  background: #f0fdf4;
}
input:required {
  border-left: 4px solid #f97316;
}

๐Ÿ’ก Empty required fields are :invalid until user types something.

โš™๏ธ LEVEL 3: Custom JavaScript (Full Control)

Why? Real-time messages, complex rules, better UX.

function validateEmail() {
  const email = input.value.trim();
  const regex = /^[^\s@]+@([^\s@]+\.)+[^\s@]+$/;
  if (!regex.test(email)) {
    showError("Invalid email");
    return false;
  }
  clearError();
  return true;
}

input.addEventListener('input', validateEmail);

form.addEventListener('submit', (e) => {
  if (!validateEmail()) {
    e.preventDefault(); // STOP submission
  }
});
๐ŸŽฏ Key pattern: Validate on input (real-time) + on submit (final check) + preventDefault()
๐Ÿš€ LEVEL 4: Advanced + Password Strength

Password strength meter logic:

const hasNumber = /\d/;
const hasLetter = /[A-Za-z]/;
const hasSpecial = /[!@#$%^&*]/;
let score = 0;
if (pwd.length >= 8) score++;
if (hasNumber.test(pwd) && hasLetter.test(pwd)) score++;
if (hasSpecial.test(pwd)) score++;
// score 1 = weak, 2 = medium, 3 = strong

Useful regex patterns:

ValidationRegex
Username (3-15, alnum + _)/^[A-Za-z0-9_]{3,15}$/
Email/^[^\s@]+@([^\s@]+\.)+[^\s@]+$/
Phone (10 digits)/^\d{10}$/
ZIP (5 digits)/^\d{5}$/
URL/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/i
๐Ÿ“‹ Quick Reference Cheat Sheet
WhatCode
Required fieldrequired attribute
Email typetype="email"
Number rangemin="1" max="100"
Custom patternpattern="[A-Z]{3}"
Disable browser validationnovalidate on form
Stop form submissione.preventDefault()
Live validation eventinput event
Trim whitespace.trim()
๐Ÿงช LIVE LAB โ€” Try typing now!