<input id="name" type="text" required>
<p id="error"></p>
<script>
document.getElementById("name").onblur = function() {
// Check if the name field is empty
if (this.value === '') {
// Set a custom error message
this.setCustomValidity("Please enter your name.");
} else {
// Clear the custom error message
this.setCustomValidity("");
}
};
</script>
In this example, the name field is required. If the name field is empty, the setCustomValidity() method will set a custom error message to "Please enter your name." If the name field is not empty, the setCustomValidity() method will clear the custom error message.
The setCustomValidity() method can also be used to set custom error messages for other types of form validation errors. For example, the following code sets a custom error message for a form field that is too short:
Code snippet
<input id="password" type="password" required minlength="8">
<p id="error"></p>
<script>
document.getElementById("password").onblur = function() {
// Check if the password field is too short
if (this.value.length < 8) {
// Set a custom error message
this.setCustomValidity("The password must be at least 8 characters long.");
} else {
// Clear the custom error message
this.setCustomValidity("");
}
};
</script>
By using the setCustomValidity() method, you can customize the error messages that are displayed for form validation errors. This can help users to understand why their form is not valid and how to correct the errors.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The setCustomValidity() method of the HTMLObjectElement interface sets a custom validity message for the element.
Here is an example of how to apply custom error messages for form validation errors using the setCustomValidity() method:
Code snippet
In this example, the name field is required. If the name field is empty, the setCustomValidity() method will set a custom error message to "Please enter your name." If the name field is not empty, the setCustomValidity() method will clear the custom error message.
The setCustomValidity() method can also be used to set custom error messages for other types of form validation errors. For example, the following code sets a custom error message for a form field that is too short:
Code snippet
By using the setCustomValidity() method, you can customize the error messages that are displayed for form validation errors. This can help users to understand why their form is not valid and how to correct the errors.