Course contentsShow
← Web Development
Lesson 917 of 2,98216. Forms and ValidationFree lesson

Custom Error Message Display

Replace browser default error tooltips with custom-styled error messages for better UX.

Custom Error Message Display

What you'll learn: How to replace the browser's built-in error tooltips with your own custom-styled error messages for a more polished and consistent user experience.

Why Custom Error Display Matters

By default, when HTML5 form validation fails, browsers show a standard tooltip near the invalid field. These tooltips look different across browsers and can't be styled to match your design. For professional applications, you want error messages that fit your brand and are consistently positioned.

The Core Technique

You've already learned about setCustomValidity() and the invalid event. Now combine these with DOM manipulation to create custom error displays:

  1. Prevent default validation UI using novalidate on your form (or handle it programmatically)
  2. Listen for the invalid event on inputs
  3. Display your own error container (a <span>, <div>, or styled element)
  4. Populate it with the validationMessage from the input
const emailInput = document.getElementById('email');
const errorDisplay = document.getElementById('email-error');

emailInput.addEventListener('invalid', (e) => {
  e.preventDefault(); // Stop browser tooltip
  errorDisplay.textContent = emailInput.validationMessage;
  errorDisplay.style.display = 'block';
});

emailInput.addEventListener('input', () => {
  if (emailInput.validity.valid) {
    errorDisplay.style.display = 'none';
  }
});

Think of It Like This

Instead of letting the browser shout errors through a megaphone (the default tooltip), you're giving validation a microphone connected to speakers you control—positioned exactly where you want, styled however you need.

Key Takeaway: Custom error display uses the invalid event to intercept validation failures and show errors in your own styled elements, giving you complete control over error presentation and user experience.