Remove Invalid File uploaded to input type=file in JavaScript

bikashgosai

bikashgosai

Posted on December 19, 2022

Remove Invalid File uploaded to input type=file in JavaScript

Here input parameter is the html element, span is label for filenames.

var readURL = function (input, span) {
    var text = "";
    let fileName = "";
    let isValid = false;
    var files = $(input)[0].files;
    var fileArray = Array.from(files);

    for (var i in files) {
        if ($(files)[i] && typeof $(files)[i]['name'] != "undefined") {

            fileName = $(files)[i].name;
            isValid = checkFileValidation(fileName);

            response.fileName.push(fileName);
            response.valid.push(isValid);

            if (isValid) {
                text += " " + $(files)[i]['name'];
            }
            else {
                fileArray.splice(i, 1);
            }
        }
    }
    $(input)[0].files = new FileListItems(fileArray);

    if (text == "") {
        text = "Upload";
    }
    $('#' + span).text(text);
};
Enter fullscreen mode Exit fullscreen mode
var validFileExtensions = "^.*\.(pdf|jpg|jpeg|gif|png|bmp|doc|docx|ppsx|ppt|pptx|xls|xlsx|7z|zip|rar|csv|txt|rtf|m4a|mp3|mpeg|avi|mpeg4|real|wav|swf|wma|msg)$"
var checkFileValidation = function (fileOrFileName) {
    //Check whether the file is valid file.
    var regex = new RegExp(validFileExtensions);
    if (regex.test(fileOrFileName.toLowerCase())) {
        return true;
    } else {
        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bikashgosai
bikashgosai

Posted on December 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related