The validationMessage Property
What You'll Learn
You'll learn how to retrieve the browser's built-in error message that explains why a form field failed validation.
Understanding validationMessage
When a form input fails constraint validation (like missing a required field or not matching a pattern), the browser automatically generates a helpful error message. The validationMessage property gives you direct access to that message.
Think of validationMessage as reading the note the browser wrote explaining what went wrong. If the input is valid, this property returns an empty string. If invalid, it contains a human-readable message like "Please fill out this field" or "Please match the requested format."
How It Works
The validationMessage property is read-only and lives on every form control element. It pairs perfectly with the validity state you learned about earlier:
const emailInput = document.querySelector('#email');
emailInput.addEventListener('blur', function() {
if (!emailInput.checkValidity()) {
console.log(emailInput.validationMessage);
// Might show: "Please include an '@' in the email address"
}
});
This is particularly useful when you want to display custom error messages in your own UI instead of relying on the browser's default tooltip bubbles:
const errorDisplay = document.querySelector('#error-message');
if (!emailInput.checkValidity()) {
errorDisplay.textContent = emailInput.validationMessage;
errorDisplay.style.display = 'block';
}
When validationMessage is Empty
If the field passes all constraints, validationMessage returns an empty string (""), signaling there's nothing wrong to report.
Key Takeaway: The validationMessage property provides the browser's default error message for failed validation, giving you a ready-made, user-friendly explanation of what needs to be fixed without writing custom messages for every constraint type.