JQuery custom html5 error messages

I use HTML5 to validate the form and change the text of the error message using setCustomValidity. Except that for some reason I cannot get this to work. I have no error messages in the console or anything else. I am trying to take what is in the "data error" attribute and use this as a custom error message, but I can not figure it out. I spent a few hours on it.

JQuery

$aboutUs.find("#headerForm :input").each(function(){ var $this = $(this); var errorMessage = $this.attr("data-error"); for (var i = 0; i < $this.length; i++) { $this[i].oninvalid = function(e) { e.target.setCustomValidity("test"); if (!e.target.validity.valid) { e.target.setCustomValidity(e.target.getAttribute(errorMessage)); } }; } }); 

HTML FORMAT

 <input id="firstName" type="text" required data-error="First Name Message" /> <input id="lastName" type="text" required data-error="Last Name Message" /> <input id="phone" type="text" required data-error="Phone Message" /> 
+4
source share
1 answer

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); } }); 
+8
source

Source: https://habr.com/ru/post/1485724/


All Articles