Most browsers have default error messages displayed when required form inputs are empty or invalid (Safari is the notable exception). I like the styling of these messages, so rather than create my own I would be happy to display the browser defaults. There are three ways in which these default messages get displayed:
- A user attempts to submit the form
- You programmatically click the submit button of the form
- You use
reportValidity()
reportValidity() on blur is easy enough:
var form = document.forms[0];
var inputs = form.querySelectorAll("input");
inputs.forEach((input) => input.addEventListener("blur", function() {
input.reportValidity();
}))
The behaviour of reportValidity() differs across browsers. Chrome shows the error message, but also has the incredibly un-user friendly effect of trapping the cursor inside the erronous input element - clicking another input or using the tab key has no effect, which is a terrible user experience. Chrome also displays the error message of whichever invalid input field is earliest in the source order. Firefox (tested on Nightly) has my desired behaviour of displaying the error message of only the relevant input, and doesn't trap the users cursor.
Is there a way to display the error message for the input field that the blur event happened on (on all browser that have default error messages)?