I'm trying to understand why I can't get browser validation error messages to show based on HTML validation.
I have a field in my markup that I want to validate, and a link that investigates its validity in order to know whether to fire on click. Notably, this isn't within a form, and from reading of the HTML spec it's not clear to me if that's an issue. Certainly, the fact I can use the checkValidity method for a field outside of a form suggests to me it's worth looking at.
HTML
<input type="email" id="email" required="required">
<a id="link" href="some_external_link" target="_blank">Do the thing</a>
JavaScript/jQuery
$("#link").on("click", function(event) {
var email = $('#email')[0];
if (!email.checkValidity()) {
event.preventDefault();
}
});
From the behaviour I've seen so far, when I put it in an invalid e-mail address and try to click the link, I would expect this to (based on the spec) fire a "simple event", which, as I understand it, is what browser error message display must be hooked into.
But instead no validation messages appear. The validation does fail and the link follow is prevented, and the reverse is true if I fill in a valid e-mail. Am I missing something about how the event is fired or handled?
There's other answers that involve creating a form and submit button around the field, which will be my last resort, but that's a lot of extra meaningless noise to get the desired functionality, and I'd like to understand the root causes of what I'm seeing.
As far as I can see, there is no external event that can be hooked into - the browsers don't publish anything from an individual element as it is validated, but rather do all the work internally as they process a form.
There is a method called reportValidity()
in some early W3C docs, which is available in Chrome and on the list for possible Firefox features, and although isn't enough to mean it's usable yet, this helped to point out that checkValidity()
doesn't show the validation errors to a user by itself.
If you want to get this functionality for the moment, you'll either have to wrap your controls in a form and suppress its default submitting behaviour in Javascript, or signal the failed validation to the user in a way other than the browser's default implementation.