adamdehaven
adamdehaven

Reputation: 5920

Javascript Detect Name of file chosen to attach to form, and alert if user selects wrong file

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?

Upvotes: 1

Views: 3114

Answers (5)

fred2
fred2

Reputation: 1110

  1. Disable HTML submission of form. HTML submission will get priority over JS otherwise.
  2. Add onclick/click event to submission button.
  3. Click event calls a function that validates your data.
  4. If data ok, submit form by JavaScript.

    <script>
       function validate(){
    
        if (document.getElementById('dealers_csv').value != 'mcust.csv'){
            alert('Filename must be mcust.csv');
        }else{
            document.getElementById('upload-form').submit();
        }
     }
    </script>
    
    
    <form name="upload-form" id="upload-form" enctype="multipart/form-data" method="post">
    
       <input type="file" name="dealers_csv" id="dealers_csv">
    
       <input type="button" value="Submit" onclick="validate()"/>
    
     </form>
    

Upvotes: 2

Nemoy
Nemoy

Reputation: 3427

I think you are using JQuery tools validator. Here is the modified code for validation.

HTML

<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" filename="mcust.csv">

<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>

Javascript

$(document).ready(function () {

  //definfing custom validator
    $.tools.validator.fn("[filename]", function(input, value) {
        var fName = input.attr("filename"),
            regX = new RegExp('.*\\' + fName + '$');
        if (value.match(regX)) {
            return true;
        } else {
            return {
                en : "Wrong file! Please select '" + fName + "'"
            };                                
        }        
    });

   // assigning validator to file input
    $("#dealers_csv").validator({
        position: 'top center',
        offset: [-12, 40],
        relative: true,
        message: '<div><em></em></div>'
    });

    //triggering validation on change of file
    $("#dealers_csv").change(function(){
       $(this).data("validator").checkValidity();    
    });    
});

try to understand this code and modify it for your needs

Upvotes: 1

Nemoy
Nemoy

Reputation: 3427

Modify your change event handler to this:

$(document).ready(function () {
    $("#dealers_csv").change(function(){
        var dealers =$(this).val();
        if(!dealers.match(/.*\\mcust.csv$/g)){
            alert("Wrong file!" + dealers);
            this.value = "";
            return false;
        }
     });
});

Here is the fiddle http://jsfiddle.net/NYwns/1/

Upvotes: 0

ramblinjan
ramblinjan

Reputation: 6694

This has been answered here https://stackoverflow.com/a/651767/437226
This will check the extension.

To check the file name without an excessive amount of code, put in a hidden field:

<input id="attachmentname" type="hidden" value="mcust.csv" />

Then in the rules add an equivalency checker:

$("#myform").validate({
  rules: {
    attachment: {
      equalTo: "#attachmentname"
    }
  }
});

Upvotes: 1

bPratik
bPratik

Reputation: 7019

This: http://jsfiddle.net/pratik136/DpJYe/ should answer your question

EDIT: fiddle updated to reflect your form submit requirement

Upvotes: 1

Related Questions