I'm using HTML5 to validate a form and change the error message text using setCustomValidity. Except for some reason I just can't get this to work. I'm getting no error messages in the console or anything. I'm trying to take what is in the "data-error" attribute and use that as the custom error message but can't figure this out I've spent hours on this.
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 FORM
<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" />
Your statement var errorMessage = $this.attr("data-error");
already gets the message, and then you are trying to get the attribute with the name as that of the message. e.target.setCustomValidity(e.target.getAttribute(errorMessage));
. errorMessage
in this statement is the message not the attribute name instead it is the message itself. So you probably meant e.target.setCustomValidity(errorMessage);
By the way you could just use $this.data("error")
to retrieve the data-*
value, provided it doesn't change on the fly.
So try this:-
$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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With