HTML5 > Forms Elements

Showing custom validation error in HTML5

How to show custom validation error message in HTML5 form?

As we all know that there is no uniformity in the form element validation messages comes in different browsers. To make these error messages uniform, we can set custom error message so that all browser displays the same error message.

This solution is not full proof however it works in most modern browser except Internet Explorere 10.

First we have created a simple form with a textbox, email and url textbox.

 <form action="somepage.html" method="post">
            <input type="text" id="myName" name="myName" required
                   placeholder="Please enter your name" data-error="Name is required" />*
            <br />
            <input name="myEmail" id="myEmail" type="email" required 
                placeholder="Enter email" data-error="Email is required in" />
            <br />
            <input type="url" id="myUrl" name="myUrl" />
            <input type="submit" id="mySubmit" name="mySubmit" />

In the above all other element and its attributes are normal except the data-error attribute. Attribute starts with "data-" is a special type of attribute introduced in HTML 5 that can be used to hold that element specific data. It doesn't have any meaning to the browser. It is used only for the developer to hold some temporary data.

In this case, we are holding our custom error message into the data-error attribute.

Now write following jQuery code (Do not forget to refer the jQuery file into the page).

        $(function () {
            var inputs = document.getElementsByTagName("INPUT");
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].oninvalid = function (e) {
                    if (! {

In the above jQuery code we are doing following

  • getting all input element of the page using getElementsByTagNam function of JavaScript
  • looping through all of them
  • setting oninvalid event function on each element that executes only when the element is marked as invalid by the browser
  • setting its customValidity to empty so that the default error message of the browser is set to empty
  • after checking if that element is not valid, setting its customValidity to that particular element's "data-error" attribute value.


Custom validation error in html 5 form


If data-error attribute is not specified for a particular element, few browser like Firefox may display "null" is the element is invalid (like in this case, notice that we do not have data-error attribute in the URL textbox). So it is suggested to always set data-error attribute to each input type element.

 Views: 668 | Post Order: 99

Write for us