Thursday, August 4, 2011

jQuery Validator Plugin - File upload validation issue : Solved

Hi folks, have you had an issue in validating file upload with jQuery Validatior Plugin.
Sample:
$("#check").validate({
        rules: {
            myfile: {required: true,
                        accept: "png|jpg|gif|jpeg"
                      },
            },
        messages: {myfile: "ERROR"    }
    });

here it checks for file having jpg,png,gif,jpeg extension and it works. But the problem is the if we make a file with name 'foo_bar.1jpg', the validator will take this as a valid file also. Here their plug-in fails....

So i have modified the plug-in code so that it will take only having valid image extension.

Just replace the accept function in the jquery.validate.js to the below code,


accept: function(value, element, param) {
            var truncate = value.split(".");
            value = truncate[1];
            param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
            return this.optional(element) || value.match(new RegExp("^(" + param + ")$", "i"));
        },

No comments:

Popular Posts