I’m using jQuery validator() to display HTML form ‘data-message’ if the field is invalid. Is there a way call the data-message on command?
For example, instead of my JS throwing an alert with
alert("Wrong file!");
I would like to instead show the data-message from the HTML form.
Here’s my form input file field:
<input type="file" name="orders_csv" id="orders_csv" required="required" data-message="Please attach the morders.csv file.">
And here’s my current JS:
$(document).ready(function () {
$("#upload-form").validator({
position: 'top center',
offset: [-12, 40],
relative: true,
accept: "csv",
message: '<div><em></em></div>'
})
// make sure that mcust.csv is the attached file. If not, throw alert message
$("input#dealers_csv").on("change", function() {
$('#loader').hide();
var dealers = $("input#dealers_csv");
var arrfilepath = dealers.val().split("\\");
var filename = arrfilepath[arrfilepath.length - 1];
if (filename != "mcust.csv") {
alert($("#dealers_csv").data("message"));
dealers.val('');
}
});
// make sure that morders.csv is the attached file. If not, throw alert message
$("input#orders_csv").on("change", function() {
$('#loader').hide();
var orders = $("input#orders_csv");
var arrfilepath2 = orders.val().split("\\");
var filename2 = arrfilepath2[arrfilepath2.length - 1];
if (filename2 != "morders.csv") {
alert($("#orders_csv").data("message"));
orders.val('');
}
});
This will grab the form element’s data-message attribute:
It works with jQuery 1.43 and above. See the jQuery docs here. Put this in whatever response mechanism you have for your validation (alert, jQuery UI popup, etc.).
You’re using jQuery Tools for validation, it seems. To do what you want, to get the right tooltip to appear, you need to actually add a validation routine to the validator. Here’s how I believe it should go:
Add this validation routine after your call to
$("#upload-form").validator(). And remove most of the.change()event handlers, leaving only the following:Here’s the complete code:
Principle difference between this code and your original is that, when failing validation for the upload inputs, it doesn’t clear the value in them; your previous version did. I thought that clearing the input was kind of antithetical to validation, and felt wrong placing it in the validation routine.