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 ?
The Form Object in HTML DOM is used to represent the HTML < form > element. This tag is used to set or get the properties of < form > element. This element can be accessed by using getElementById() method.
As pointed out by @Zirak, there is the checkValidity
method, part of the Constraint Validation API.
var s = document.createElement('input');
s.checkValidity(); // true
s.required = true;
s.checkValidity(); // false
However, checkValidity
fires an invalid event if it's invalid. (The form will be red-outlined.) You may want to use the willValidate
property (or the .validity.valid
property) instead.
Also, the validity
property is quite interesting to watch (more information about what each property means on the Constraint Validation API):
s.validity
ValidityState
customError: false
patternMismatch: false
rangeOverflow: false
rangeUnderflow: false
stepMismatch: false
tooLong: false
typeMismatch: false
valid: false
valueMissing: true
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 invalid
event, triggered on submit of the form, or when the checkValidity
method is called.
Demo: http://jsfiddle.net/XfV4z/
The input elements have a validity
property:
var i = document.getElementsByTagName('input')[0]
i.validity.valid // True or false
console.log(i.validity);
// Logs (when `1` is entered):
ValidityState
customError: false
patternMismatch: false
rangeOverflow: false
rangeUnderflow: false
stepMismatch: false
tooLong: false
typeMismatch: false
valid: true
valueMissing: false
For more detailed info I'm not going to copy, check Florian Margaine's answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With