Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation - required working but accept not

im uploading an image and trying to validate it before with jquery. Here is my code:

<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<script type='text/javascript'>
$(document).ready(function(){
    $("#form").validate({
        errorLabelContainer: "#message_box", wrapper: "li",

        rules: {
            image: {required: true, accept: "jpg|jpeg|png|gif"}
        },
        messages: {
            image: {required: 'Required!', accept: 'Not an image!'}
        }
    })
});
</script>

Required is working - if i insert no image i get an error. But accept isn't working (anything i insert passes) and i cant figure out why. Any ideas? :)

like image 881
user1985273 Avatar asked May 01 '13 16:05

user1985273


1 Answers

You need two things.

(1) use valid syntax for using accept method because it requires you to use to provide comma-separated list of mimetypes.

$(document).ready(function(){
    $("#form").validate({
        errorLabelContainer: "#message_box", wrapper: "li",

        rules: {
            image: {required: true, accept: "image/jpg,image/jpeg,image/png,image/gif"}
        },
        messages: {
            image: {required: 'Required!', accept: 'Not an image!'}
        }
    })
});  

(2) You'll have to include the additional-methods.js because the accept methods is not included in the core validate plugin. So add following to your <head> after you include validate plugin

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>

Here's the link to jsfiddle. Note that it includes debug: true to prevent posting of the form in fiddle.

like image 197
Ejaz Avatar answered Oct 22 '22 16:10

Ejaz