as you might know, within the HTML5 spec we got some new attributes for <input> elements, such as required and pattern. This provides as a great way of validating user-input and we can even visualize it using CSS and pseudo selectors. Example
HTML
<input type="number" pattern="\d+" required/>
CSS
input:required:valid {
border: 1px solid green;
}
input:required:invalid {
border: 1px solid red;
}
If that <input> element would be part of an <form> element, an user wouldn’t be able to submit that in invalid state.
However, my question is, what if we want to use those new attributes without <form> elements ? Is there a way to access the current state of such an <input> node through ECMAscript directly ?
Any event ? Any listener ?
As pointed out by @Zirak, there is the
checkValiditymethod, part of the Constraint Validation API.However,
checkValidityfires an invalid event if it’s invalid. (The form will be red-outlined.) You may want to use thewillValidateproperty (or the.validity.validproperty) instead.Also, the
validityproperty is quite interesting to watch (more information about what each property means on the Constraint Validation API):This article points out the differences in implementations between the browsers: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/ (i.e: it’s a mess, as usual.)
You can also listen to the
invalidevent, triggered on submit of the form, or when thecheckValiditymethod is called.Demo: http://jsfiddle.net/XfV4z/