17
votes

I'm trying to use HTML5 client-side validation outside a form/submit context, but cannot see how to display the validation error bubbles. Consider the following:

<input type="text" id="input" pattern="[0-9]" required oninvalid="alert('yes, invalid')">
<button onclick="alert(document.getElementById('input').checkValidity())">Check</button>

Everything works as expected, with the correct value being returned from checkValidity, and the invalid event being sent and displayed, but how do I programmatically display the validation error bubble?

3

3 Answers

5
votes

If you're talking about this bubble:

Validation bubble in Firefox

See ScottR's comment to this answer instead.

...then my testing shows that both Firefox and Chrome display it when calling checkValidity on an element wrapped in a <form> (testcase), but not on a standalone element (testcase).

There doesn't seem to be a mechanism to display it when there's no form, and the spec doesn't even say it has to be displayed in response to programmatic checkValidity calls (on the element or the form) -- only when submitting a form.

So for now, wrap your elements in a form, even if you will not actually submit it.

Better yet, use your own validation UI, this will shield you from future changes in the browsers in this underspecified area.

0
votes

Try using required="required" and getting rid of the oninvalid handler unless you really need it.

http://blog.mozilla.com/webdev/2011/03/14/html5-form-validation-on-sumo/

Example of this working: https://support.mozilla.com/en-US/users/register

-1
votes

Just set manually "invalid" attribute to incorrect fields. Small example:

var form = $('#myForm').get(0);
if(typeof formItem.checkValidity != 'undefined' && !formItem.checkValidity()) {
    $('input:required').each(function(cnt, item) {
        if(!$(item).val()) {
            $(item).attr('invalid', 'invalid');
        }
    });
    return false;
}