Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the HTML5 validity state of an input text box?

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?

like image 698
Raman Srinivasan Avatar asked May 19 '13 12:05

Raman Srinivasan


People also ask

How do you validate a text field in HTML?

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.

How do I check if HTML input is valid?

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 .

Which are the correct input restriction used for validation purposes in HTML5?

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.


2 Answers

You can use validity property:

var isValid = document.getElementById('email').validity.valid;

Or checkValidity() method:

var isValid = document.getElementById('email').checkValidity();

Demo | Reference.

like image 111
undefined Avatar answered Dec 04 '22 21:12

undefined


There is an event oninvalid for invalid input, you can register the event if you want to act on it.

like image 31
Benny Ng Avatar answered Dec 04 '22 20:12

Benny Ng