bgs bgs - 14 days ago 9
jQuery Question

Javascript inArray not working

I have using html file upload control in

asp .net
, try to restrict the file extension in script block. For fixed file extensions
(.pdf,.txt,.doc,.docx,.xls,.xlsx,.eml,.msg)
in
inArray
it has working fine. When checking the same in array variable
(array1)
it is not working.

Code :

var AllowedFileExtensions = ".pdf,.txt,.doc,.docx,.xls,.xlsx,.eml,.msg";
var array1 = new Array();
array1 = AllowedFileExtensions.split(",");
for (var i = 0; i < array1.length; i++) {
array1[i] = "'" + array1[i] + "'";
}

var ext = $('#fileDocUpload').val().split('.').pop().toLowerCase();
ext = '.' + ext;

alert([array1]); // it throws the text = '.pdf','.txt','.doc','.docx','.xls','.xlsx','.eml','.msg'
alert(ext); // .pdf


This Code worked fine :

If ($.inArray(ext, ['.pdf','.txt','.doc','.docx','.xls','.xlsx','.eml','.msg']) == -1) {
if ($.inArray(ext.toString, array1) == -1) {
alert('invalid extension!');
return false
}


This Code not worked :

if ($.inArray(ext.toString, array1) == -1) {
alert('invalid extension!');
return false
}

Answer

That is because you are modifying the array1 to put extra quotes in each value. which modifies the array to:

["'.pdf'", "'.txt'", "'.doc'", "'.docx'", "'.xls'", "'.xlsx'", "'.eml'", "'.msg'"]

You dont need to put the value in quotes. .split() will handle it when converting the values to array here:

var array1 = AllowedFileExtensions.split(",");
if ($.inArray(ext.toString, array1) == -1) {
    alert('invalid extension!');
    return false 
}