← Blog/JavaScript

Build Professional Form Validation with JavaScript — No Libraries Needed

Learn how to build form validation from scratch with JavaScript — real-time feedback, beautiful error states, password strength meter, and 8 field types including email, phone, select, and checkbox.

📅 2026-06-262 min read📚 Ebook #13

Why Not Use HTML5 Validation?

HTML5 has built-in validation with required, type="email", and pattern. But browser-native validation:

  • Looks different in every browser (inconsistent UX)
  • Cannot show errors in a custom location
  • Cannot validate complex rules like password strength
  • Cannot do real-time validation as the user types

Custom JavaScript validation solves all of these.

The Core Pattern

Every field follows this pattern:

  1. An <input> element
  2. A <span> below it for the error message
  3. A JavaScript function that checks the value and toggles .valid / .invalid classes
<div class="field-group">
  <label for="email">Email <span class="required">*</span></label>
  <input type="email" id="email" />
  <span class="error-msg" id="email-error">Enter a valid email</span>
</div>

Email Validation

function validateEmail() {
  const field = document.getElementById('email');
  const error = document.getElementById('email-error');
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (!field.value.trim()) {
    showError(field, error, 'Email is required');
    return false;
  }
  if (!regex.test(field.value)) {
    showError(field, error, 'Enter a valid email address');
    return false;
  }
  showValid(field, error);
  return true;
}

Password Strength Meter

Check multiple rules and score the password:

function getStrength(password) {
  let score = 0;
  if (password.length >= 8)        score++;
  if (/[A-Z]/.test(password))      score++;
  if (/[a-z]/.test(password))      score++;
  if (/[0-9]/.test(password))      score++;
  if (/[^A-Za-z0-9]/.test(password)) score++;
  return score; // 0–5
}

Run All Validators on Submit

form.addEventListener('submit', (e) => {
  e.preventDefault();
  const results = [
    validateRequired('name', 'name-error', 'Name'),
    validateEmail(),
    validatePassword(),
    validateConfirm(),
  ];
  if (results.every(r => r === true)) {
    showSuccessState();
  }
});

This is a preview. The full ebook covers 8 field types — including phone number, number range, select dropdown, and checkbox — plus real-time validation on the input event and the blur-first pattern for better UX.

Ready to Build This Yourself?

This article is a preview. The full ebook has complete code, detailed explanations, troubleshooting tips, and bonus sections — all in a downloadable PDF.

Buy Full Ebook — $1.50 in $YFIN
Pay with $YFIN on BNB Smart Chain · 30% burned permanently