Search code examples
htmlvalidationuser-input

html5 input pattern attribute not working outside a form?


this fiddle works as intended - it displays a warning when the user enters an invalid country code.

This other fiddle, without the form element, doesn't work. It seems the input's pattern attribute needs a form to validate. By the way, I'm doing a complex page without forms and I' d like to validate my input fields with `pattern. Is there a way to do that?


Solution

  • This is because the validation is part of the HTML5 form validation (http://www.w3.org/TR/html5/forms.html#client-side-form-validation). The validations are triggered when the form is submitted en when there are any errors, the submit will be cancelled.

    To trigger it manually, use the checkValidity() function on the element:

    $('input').blur(function(evt) {
        evt.target.checkValidity();
    }).bind('invalid', function(event) {
       alert('oops');
    });
    

    http://jsfiddle.net/y66vH/3/