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

The setCustomValidity() Method

Use setCustomValidity() to set custom error messages that integrate with native HTML5 validation.

The setCustomValidity() Method

You'll learn how to create custom validation error messages that work seamlessly with HTML5's native form validation system.

What It Does

The setCustomValidity() method lets you define your own validation error messages for form fields. When you call it with a non-empty string, it marks the field as invalid with your custom message. When you call it with an empty string, it clears the custom error.

Think of it like a "validation override switch"—you're telling the browser, "I've checked this field myself, and here's what the user needs to know."

How It Works

You call setCustomValidity() on a form element (like an input), passing your error message as a string:

const input = document.querySelector('#username');

// Set a custom error
input.setCustomValidity('Username must start with a letter');

// This will now fail validation
input.checkValidity(); // returns false
console.log(input.validationMessage); // "Username must start with a letter"

Important: To clear the error and mark the field as valid again, you must call it with an empty string:

// Clear the custom error
input.setCustomValidity('');

// Now validation passes (assuming no other constraints fail)
input.checkValidity(); // returns true

Typical Pattern

You'll often use this inside an event listener to validate complex rules:

input.addEventListener('input', function() {
  if (this.value.length > 0 && !/^[a-zA-Z]/.test(this.value)) {
    this.setCustomValidity('Username must start with a letter');
  } else {
    this.setCustomValidity(''); // Clear error when valid
  }
});

Key Takeaway: Use setCustomValidity() to integrate your custom validation logic with the browser's native validation UI—set a message to mark invalid, pass an empty string to mark valid.