HTML5 form required attribute. Set custom validation message? HTML5 form required attribute. Set custom validation message? javascript javascript

HTML5 form required attribute. Set custom validation message?


Here is the code to handle custom error message in HTML5:

<input type="text" id="username" required placeholder="Enter Name"  oninvalid="this.setCustomValidity('Enter User Name Here')"  oninput="this.setCustomValidity('')"/>

This part is important because it hides the error message when the user inputs new data:

oninput="this.setCustomValidity('')"


Use setCustomValidity:

document.addEventListener("DOMContentLoaded", function() {    var elements = document.getElementsByTagName("INPUT");    for (var i = 0; i < elements.length; i++) {        elements[i].oninvalid = function(e) {            e.target.setCustomValidity("");            if (!e.target.validity.valid) {                e.target.setCustomValidity("This field cannot be left blank");            }        };        elements[i].oninput = function(e) {            e.target.setCustomValidity("");        };    }})

I changed to vanilla JavaScript from Mootools as suggested by @itpastorn in the comments, but you should be able to work out the Mootools equivalent if necessary.

Edit

I've updated the code here as setCustomValidity works slightly differently to what I understood when I originally answered. If setCustomValidity is set to anything other than the empty string it will cause the field to be considered invalid; therefore you must clear it before testing validity, you can't just set it and forget.

Further edit

As pointed out in @thomasvdb's comment below, you need to clear the custom validity in some event outside of invalid otherwise there may be an extra pass through the oninvalid handler to clear it.


It's very simple to control custom messages with the help of HTML5 event oninvalid

Here is code:

<input id="UserID"  type="text" required="required"       oninvalid="this.setCustomValidity('Witinnovation')"       onvalid="this.setCustomValidity('')">

This is most important:

onvalid="this.setCustomValidity('')"