Validate Image File extension before Upload using Regular Expression in jQuery

nauna
 
on Jul 19, 2022 11:01 PM
Sample_118485.zip
791 Views

I used below script to validate file extension but if file name has any special character so it's not allowing user to select file i want only extension validation file name could be anything.

<script language="javascript" type="text/javascript">
    $(function () {
        $('[id*=fubanner]').change(function () {
            if (typeof (FileReader) != "undefined") {
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                $($(this)[0].files).each(function () {
                    var file = $(this);
                    if (regex.test(file[0].name.toLowerCase())) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            $('[id*=imgbanner]').attr("src", e.target.result).attr("style", "");
                        }
                        reader.readAsDataURL(file[0]);
                    } else {
                        alert(file[0].name + " is not a valid image file.");
                        return false;
                    }
                });
            } else {
                alert("This browser does not support HTML5 FileReader.");
            }
        });
    });
</script>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 20, 2022 12:26 AM

Hi nauna,

Use this regular expression /\.(jpg|jpeg|gif|png|bmp)$/i.

Refer below code.

HTML

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('[id*=fuFile]').change(function () {
                if (typeof (FileReader) != "undefined") {
                    var regex = /\.(jpg|jpeg|gif|png|bmp)$/i;
                    if (regex.test($('#fuFile')[0.].files[0].name.toLowerCase())) {
                        alert("Valid");
                    } else {
                        alert("Invalid");
                    }
                } else {
                    alert("This browser does not support HTML5 FileReader.");
                }
            });
        });
    </script>
    <input id="fuFile" type="file" />
</body>
</html>

Demo