I have an HTML form with an input field to upload a file. I want the file chosen to match the correct file name desired (mcust.csv). If they select a different file, I want to trigger an error with JS.
The form is shown below:
<form name="upload-form" id="upload-form" action="upload-information.php" enctype="multipart/form-data" method="post">
<input type="file" name="dealers_csv" id="dealers_csv" required="required" data-message="Please attach the mcust.csv file.">
<button type=\"submit\" name=\"Submit\" id=\"Submit\" class=\"csbutton-color upload-button\" style=\"margin-right:10px;\" >Submit files</button><img id=\"loader\" src=\"../images/loading.gif\" style=\"display:none;\"/>
</form>
After the user attaches a file, I want to detect the name of the file (mcust.csv) and if the file name is NOT mcust.csv, I want to "do something" (show an error) using Javascript/jQuery BEFORE the form is submitted.
Here's the 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() {
var dealers = $("input#dealers_csv");
var arrfilepath = dealers.val().split("\\");
var filename = arrfilepath[arrfilepath.length - 1];
if (filename != "mcust.csv") {
alert("Wrong file! Please select 'mcust.csv'");
dealers.val('');
}
});
// make sure that morders.csv is the attached file. If not, throw alert message
$("input#orders_csv").on("change", function() {
var orders = $("input#orders_csv");
var arrfilepath2 = orders.val().split("\\");
var filename2 = arrfilepath2[arrfilepath2.length - 1];
if (filename2 != "morders.csv") {
alert("Wrong file! Please select 'morders.csv'");
orders.val('');
}
});
});
EDIT: I've updated the above code to the working version. One question: Is there a way to show the data-message rather than an 'alert' if they attach the wrong file?