Kiran B Kiran B - 7 days ago 4
Javascript Question

I am facing Issue in size of file Validation in magento 1

I have an issue in validating a file in magento form validator,

i have custom validation code for file size like this.


Validation.add('validate-filesize', 'Upload file should be less than 2MB',function(v,elem) {

var file = elem.files;

var fileSize = file[0].size;

if(fileSize <= 2000000){
return true;
}
else{
return false;
}
});


and in my form there are two file filds.

above validation code is working fine for this field.

<input type="file" id="file1" name="file1" value="" class="input-text required-entry validate-filesize">


but it is failing to validate below field

<input type="file" id="file2" name="file2" value="" class="input-text validate-filesize">

Answer

The error doesn't lie in the library, but in your validator callback function.

You are checking the size of the file using the following code

var fileSize = file[0].size

But when the user doesn't upload any files, the variable file[0] is undefined. Thus when you do file[0].size, it throws an error saying Cannot read property 'size' of undefined. And that's why further processing of your code stops and you don't get the desired message.

A good way of doing it would be to check if the user has uploaded any files before checking it's size, like so.

var file = elem.files;

if(file.length == 0) return true; // all is good if user didn't upload any file

//go ahead with the rest of the code otherwise

var fileSize = file[0].size;

if(fileSize <= 2000000){
    return true;
}
else{
    return false;
}