So, what i’m tring to do is validate a file extension using javascript/jquery before send to other validation on the server side (php).
I know that has a lot of sources around here, but, i’m trying to make in my own way.
i reach a simple ideia, like the code above:
// remove all elements to take only the file name
var fileName = $('input[type=file]').val().split('\\').pop().toLowerCase();
validExtension = ['.jpg', '.png', '.gif','.jpeg']; // list of valid extensions
$.each(validExtension, function (e, val) { // run thru all valid extensions
if (fileName.indexOf(val) !== -1) { // if found a valid one, stop validation.
invalidExt = false;
return false;
} else { // else, error true...
invalidExt = true;
}
});
if (invalidExt) {
alert('error');
}else{
alert('success');
}
the problem is, if the file have a .jpg or any other valid extension in the middle of the name like desert.jpg.exe, the validation will pass thru. So, how can i solve this?
Maybe find a way to get the last extension on the file name?
And ofcourse, any tips, be my guest.
Thanks.
Here’s how I’d do it:
lastIndexOfto get the last period in the file name. This way, you’re always looking at the extension, regardless of what comes before it.