DEV Community

bikashgosai
bikashgosai

Posted on

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay