[HTML 5] How to customize the error message for a required field ?

November 16th, 2011 | Posted by Tom in HTML5 | Read: 12,157

In HTML 5, it’s possible to use the attribute required attribute of an input field to specify that this field need to be fill otherwise, a validation error is raised:

<label>Username:<sup>*</sup><input name="username" type="text" placeholder="Username" required="true" autofocus="true"/></label>

image

While this is useful and done automatically, you might prefer to customize the message that is displayed. To do that; you can use the setCustomValidity method:

$(document).ready(function () {
    var intputElements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < intputElements.length; i++) {
        intputElements[i].oninvalid = function (e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                if (e.target.name == "username") {
                    e.target.setCustomValidity("The field 'Username' cannot be left blank");
                }
                else {
                    e.target.setCustomValidity("The field 'Password' cannot be left blank");
                }
            }
        };
    }
})

Now, if an error is raised, the previous JQuery code will check the name of the field and display the correct error message:

image image

Again, a simple tip but very useful if you plan to use HTML 5 forms.

 

Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register



Leave a Reply