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

The setCustomValidity() Method

Overriding browser validation messages with custom error text for better UX.

The setCustomValidity() Method

You'll learn how to replace the browser's default validation error messages with custom text that better serves your users.

What is setCustomValidity()?

The setCustomValidity() method lets you override the browser's built-in validation messages with your own custom error text. Instead of generic messages like "Please fill out this field," you can provide context-specific, user-friendly guidance.

Think of it like replacing a vague "Error" notification with a helpful explanation: "Your password must include at least one number" is far more useful than "Please match the requested format."

How It Works

When you call setCustomValidity() with a non-empty string, the browser treats the input as invalid and displays your custom message. To clear the error and mark the field as valid again, call it with an empty string.

const emailInput = document.querySelector('#email');

emailInput.addEventListener('input', (e) => {
  if (emailInput.value.includes('@company.com')) {
    emailInput.setCustomValidity('Please use your personal email, not your work email.');
  } else {
    emailInput.setCustomValidity(''); // Clear the error
  }
});

Common Pattern

Combine setCustomValidity() with checkValidity() or reportValidity() to trigger the message display:

const passwordInput = document.querySelector('#password');

passwordInput.addEventListener('blur', () => {
  if (passwordInput.value.length < 8) {
    passwordInput.setCustomValidity('Password must be at least 8 characters long.');
    passwordInput.reportValidity(); // Show the message
  } else {
    passwordInput.setCustomValidity('');
  }
});

Key Takeaway: Use setCustomValidity() to provide clear, actionable error messages that improve user experience—just remember to clear the custom message with an empty string when validation passes.