Your expression var errorMessage = $this.attr("data-error"); already receiving the message, and then you try to get the attribute with the name like the name of the message. e.target.setCustomValidity(e.target.getAttribute(errorMessage)); . errorMessage in this statement is a message, not an attribute name, not a message . So you probably meant e.target.setCustomValidity(errorMessage);
By the way, you can simply use $this.data("error") to get the value data-* if it does not change on the fly.
So try the following: -
$aboutUs.find("#headerForm :input").each(function(){ var $this = $(this); var errorMessage = $this.data("error"); for (var i = 0; i < $this.length; i++) { $this[i].oninvalid = function(e) { if (!e.target.validity.valid) { e.target.setCustomValidity(errorMessage); } }; } });
Since you are using jquery, just simplify this:
$aboutUs.find("#headerForm :input").on('invalid', function (e) { var errorMessage = $(this).data("error"); e.target.setCustomValidity(""); if (e.target.validity.valueMissing) { e.target.setCustomValidity(errorMessage); } });
source share