Validate File extension before Upload using Regular Expression in jQuery


In this article I will explain how to validate File extension before Upload using Regular Expression (Regex) in jQuery. The selected File’s extension will be validated using a Regular Expression and an error message will be displayed when an invalid file is selected.



Html 


<form action="" method="post">
 <span id="error" style="color: red;"></span> 
 <input id="fileUpload" type="file" />  
 <input type="submit" id="btnUpload" value="Upload" /> 
</form>

jQuery


<script type="text/javascript">
    $("body").on("click", "#btnUpload", function () {
        var allowedFiles = [".doc", ".docx", ".pdf"];
        var fileUpload = $("#fileUpload");
        var error = $("#error");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.val().toLowerCase())) {
            error.html("Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.");
            return false;
        }
        error.html('');
        return true;
    });
</script>

Regular Expression for allowing Word Document and PDF files only
([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$

Regular Expression for allowing Image files only
([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$

Regular Expression for allowing Text files only
([a-zA-Z0-9\s_\\.\-:])+(.txt)$

Regular Expression for allowing Excel files only
([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$



Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.