jQuery Validator Does Not Validate Input File Type

user975343 picture user975343 · May 9, 2013 · Viewed 10.5k times · Source

I've written a upload form and I want users to be able to upload only images. I've decided to use jQuery validator in order to make sure that users cannot send an empty form an can only upload images. So far, users indeed can't send an empty form, but they can upload and file they would like to , even if it's not an image. Here's the code of jsFunc.js which aim to handle this problem:

$(document).ready(function () {
$('#upload-image').validate({
    errorElement : "span",
    errorPlacement: function(error, element) {
        error.appendTo(".upload-error");
    },
    rules: {
        pic: {
            required: true,
            accept: "image/*"
        }
    }
});
});

Here are the files included in the page that included the upload form :

<script src="bootstrap/js/jquery.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="sys/jsFunc.js"></script>
<script type="text/javascript" src="sys/additional-methods.js"></script>
<script type="text/javascript" src="sys/jquery.validate.js"></script>

What is wrong with the code above? I'd be grateful if anyone could point me to the problem.

Answer

Raji picture Raji · May 9, 2013

If you're trying to validate by file extension or to accept only images with certain extension you can use like this

rules: {
   field: {
     required: true,
     extension: "jpeg|png"
   }
}

See: http://docs.jquery.com/Plugins/Validation/CustomMethods/extension#extension