Ad Code

Validate File extension before Upload using Regular Expression in JavaScript and jQuery

Using JavaScript

<script type="text/javascript">
    function ValidateExtension() {
        var allowedFiles = [".doc", ".docx", ".pdf"];
        var fileUpload = document.getElementById("fileUpload");
        var lblError = document.getElementById("lblError");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.value.toLowerCase())) {
            lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
            return false;
        }
        lblError.innerHTML = "";
        return true;
    }
</script>
<input id="fileUpload" type="file" />
<span id="lblError" style="color: red;"></span>
<input type="submit" value="Upload" onclick="return ValidateExtension()" />

Using jQuery

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

Post a Comment

0 Comments