I have a form which includes 3 textfields so users can upload files. They must choose to upload at least 1 file and files must be jpg, png, pdf. I am trying to validate this using javascript and check if user is selected at least 1 file and the format is correct before uploading I have the following code but it dont work. I hope someone can help thanks.
My current code:
function validate_ext() {
var filename = document.getElementById("file1").value;
var filename2 = document.getElementById("file2").value;
var ext = getExt(filename);
var ext2 = getExt(filename2);
if((ext == "pdf") || (ext=="PDF") || (ext=="jpg") || (ext=="jpeg") || (ext=="png") || (ext=="PNG"))
return true;
alert("Please upload files in correct format only.");
return false;
if(filename2!=''){
if((ext2 == "pdf") || (ext2=="PDF") || (ext2=="jpg") || (ext2=="jpeg") || (ext2=="png") || (ext2=="PNG"))
return true;
alert("Please upload files in correct format only.");
return false;
}
}
function getExt(filename) {
var dot_pos = filename.lastIndexOf(".");
if(dot_pos == -1)
return "";
return filename.substr(dot_pos+1).toLowerCase();
}
(test here):
You had a couple of errors.
sjumssaid about the extension being converted to lower case, you don’t need to compare to upper case strings.true, your code just returns when it should run the second check.I also added a
return trueat the end, so the function returns this value only if it passed all the validations.