File uploader with javascript extension validation

I was recently creating a form that needed to upload an image only to an email handler.  The file would then get emailed to the client.

The way that we have always worked this, is the fileupload control posted back to the server and checked the fuImage.HasFile and then fuImage.FileName, maybe even using the FileInfo class to let it grab the extension, and check it against a list.

But I realised that is real old school, and with the loveliness of jQuery and regular expressions. Again the internet failed me almost, as there are not really good posts or helpers out there that do this. Everything that appears seems to be out of date, or does something similar but not what am wanting. Well here is a quick script to check the file extensions and inform the user if the file is an image or not:

$(document).ready(function () {

        $("#btnRegister").click(function () {
            // check if the file you are going to upload is an image or not.
            var filePath = $("#fileUpload").val();
            filePath = filePath.replace(/^\s|\s$/g, "");
            if (/\.\w+$/.test(filePath)) {
                var m = filePath.match(/([^\/\\]+)\.(\w+)$/);
                if (m) {
                    if (m[2] == "gif" || m[2] == "jpg" || m[2] == "png" || m[2] == "bmp") {
                        return true;

            alert("Please make sure you upload only pictures.");
            return false;



And that’s it. You can quite easily change the file extensions here to suit your needs, even try and do something fancy with call backs to the server with the file extension so you can read a dynamic list or from a config file or something, how should I know that’s you job fs!!

2 thoughts on “File uploader with javascript extension validation”

Leave a Reply

Your email address will not be published.