HEEN
HEEN

Reputation: 4721

Javascript alert is prompting twice in IE

I have a file validation for uploading only xls files. But if I am uploading files other than excel, than its prompting the error properly.

But the issue is the alert is firing twice in IE

Below is my code.

function isFileValid() {
        var allowedFiles = [".xlsx", ".xls"];
        var fileUpload = document.getElementById("MainContent_fluploadData");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");

        if (!regex.test(fileUpload.value.toLowerCase())) {                
            alert("Please upload files having extensions: " + allowedFiles.join(', ') + " only.");               
            $('#MainContent_fluploadData').val('');
            return false;
        }            
    }

HTML

<asp:FileUpload ID="fluploadData" Style="padding-top: 0px; padding-left: 0px; padding-bottom: 0px; padding-right: 0px;" CssClass="form-control" runat="server" onchange="return isFileValid();" />

NOTE

I am using the file upload control inside update panel

Upvotes: 1

Views: 231

Answers (1)

Joshua T
Joshua T

Reputation: 2589

To summarize the conclusion reached in the comments and the solution; this bug is caused by a difference in how IE handles onchange events for input elements, vs other browsers. For IE, when you change the value of a file input element programatically, like you are doing with $('#MainContent_fluploadData').val('');, it actually causes another onchange event to be emitted, whereas it does not in other browsers. Most other browser do not re-emit the onchange event in this scenario.

The easiest solution in this scenario is to just add a check to see if your own code has already reverted the input field back to "" (no file selected), by modifying your IF statement from:

if (!regex.test(fileUpload.value.toLowerCase()))

to:

if (!regex.test(fileUpload.value.toLowerCase()) && fileUpload.value!=='')

If you start doing something like reverting to the last value instead of to an empty string (unselected file), you would want to do something like hold the value of the last checked filename as a variable outside that function, then check it against the new filename to see if the file selection has actually changed.


For more info:

Upvotes: 3

Related Questions