Using Validation and Vibration API in HTML5

HTML5 provides bevy of features which enable developers to build some really interesting applications. In this example I will build a small HTML5 based validation which will vibrate the mobile device in case of invalid input.

Validation API

Validation in HTML5 is as simple as adding an attribute. Just add the required attribute and you are good to go.

In the above code snippet the text field is required and browser supporting this attribute will not let you submit the form if the field value is empty.

Now we need to check if the user has entered valid value in the field or not. It he hasn’t then we vibrate the mobile device. To check it in JavaScript use the statement input.validity.valid. This returns true in case valid value is entered in the field else returns false. In case its invalid you can then vibrate the mobile device using Vibration API.

Vibration API

This article describes Vibration API and how easy it is to implement.

First you need check if the device supports Vibration API:

Then check the prefixed versions:

Then vibrate the device by calling:

Putting everything together

So you have an input field like this:

When user exits this field we call a function check(this) which checks if a valid value is entered in it or not. In this case the field cannot be empty. Here’s how the function would be:

Here if input.validity.valid returns false then we set the class of input to invalidInput. Using CSS we style the input to show a red border around it and an exclamation mark. And then we vibrate the device three times.

This is how we style the invalidInput:

You can also validate for a particular pattern, email input, URL input and more. Just make sure you include the required=”required” attribute. For e.g.:

Below is the entire HTML code for my example. Go ahead and give it a try on your mobile.

Screenshots for Google Chrome 36, Mozilla Firefox 31 and Opera 22 on Android
Share:

Leave a Reply

Your email address will not be published. Required fields are marked *