Testing HTML 5 Validation from JavaScript

In the rare circumstance where you need additional validation client side beyond that now provided by the HTML 5 required and pattern attributes you can add just that extra validation using JavaScript without needing to replicate the HTML validation in the JavaScript.

The properties associated with the the input field contain a number of validity flags, one of which indicates whether the field passes the validation built into the HTML.

Let's assume we have a basic input tag with an id and a required attribute.

<input id="a" type="text" required>

The required attribute means that the field will only be valid if something is entered into it and the id gives us a way to attach both a label and some JavaScript to the field. Your actual input field may have additional attributes but these are sufficient to demonstrate how we can check that the HTML validation is met before applying additional validation in JavaScript.

Let's attach a blur event listener to the input field so we can check the field when the field loses focus (you would of course apply whichever event you need should blur not be the right one for your situation).

var a = document.getElementById('a');
  a.addEventListener('blur',function() {console.log(a.validity.valid)}, false);

With this code all we are doing is writing a flag associated with the input field to the console when the field loses focus. The value that is written will be either true or false depending on whether something was entered into the field or not (since the field only passes HTML validation for required when something is entered in the field).

Now that we know what property to reference for the field to test the HTML validation we can easily use an if statement to test whether the various fields pass HTML validation before proceeding to add the additional validations you need that can't be applied by the HTML and which you therefore have decided to apply via JavaScript.

So the actual code in our JavaScript might look like this with the additional validations in lace of the ... in the following.


if (document.getElementById('a').validity.valid) { ... }

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate