views:

57

answers:

1

Hello.

I'm coding a form using PHP and jQuery. I have a file upload field to which I applied the following jQuery-validate rules:

image: {
 accept: "jpeg|jpg|png|gif",
 required: "#edit_ID:blank"
}

The file upload field must only accept jpeg/jpg, png, or gif images. It is required only if the field with the ID "edit_ID" is left blank.

This is my file upload field:

<input type="file" id="image" name="image" class="input1" />

The file upload field selects files without any problem, but when jQuery returns an error because of a violated rule, even if I select a new file from my computer the file I selected before the error appeared remains there. It's as if it becomes disabled after jQuery-validate gives an error.

I tried removing the rules set for this field, tested it, and encountered no problem.

Does anybody have an idea what's causing this problem?

Thanks.

P.S.: I encounter the problem in Firefox (v.3.6.9) and IE (v.8) but not in Google Chrome (v.5).

A: 

This will not answer your original question, technically.

But, it's not a good idea to trust client side programming to do image validation; your program can be fooled. Since you are using PHP anyway, why not use PHP to do some server side validation?

All files uploaded are stored in the $_FILES array. You can check file type like so:

<?php
    foreach($_FILES as $file)
    {
        if(!empty($file['type'])) //only check if there's a valid file type
        {
            if($file['type'] != 'image/jpeg' && $file['type'] != 'image/png' && $file['type'] != 'image/gif')
            {
                //this file is not any one of the accepted formats, so long!
            }
            else{//do your processing}
        }
        else{//error invalid file}
    }
?>

In case you want instant validations, you can still use AJAX, instead of relying solely on the client side to do the validation.

Aditya Menon
I prefer to use client side validation so that the user isn't taken to a different page before errors are shown. If I don't figure out how to solve the jQuery problem then maybe I'll just use PHP.
Catzie
You can use AJAX if you don't like the user going to another page...
Aditya Menon
I'll try that. Thanks.
Catzie