How can I retrieve the HTML 5 'validity' status of a text box?
For instance, I have a text input with type="email"
. When the user enters the wrong value, the text box shows a red border (in Firefox browser).
How can I check the 'validity-state' of the input box?
To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.
Using the email type, we can check the validity of the form field with a javascript function called… checkValidity() . This function returns a true|false value. checkValidity() will look at the input type as well as if the required attribute was set and any pattern="" tag .
Note: Several of these HTML5 input types have additional parameters to help limit and validate the input. They include: maxlength defines the maximum length of a text field. min and max define the minimum and maximum of number and range fields.
You can use validity
property:
var isValid = document.getElementById('email').validity.valid;
Or checkValidity()
method:
var isValid = document.getElementById('email').checkValidity();
Demo | Reference.
There is an event oninvalid
for invalid input, you can register the event if you want to act on it.
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