views:

239

answers:

2

How to get an field required with the jQuery Validation plugin ? Couldnt find this one in the doc/demos.

I mean there's the option for an email which is class="required email" same for a number class="required number" but nothing about a file input.

+1  A: 

Just try using the

class='required error'

to ensure there's something in the field. The class="required email" and class="required number" look for certain patterns.

If you want to ensure the upload has .jpg in the filename then write a custom rule to check for those characters.

niggles
Just tried, doesnt work.
kevin
i would need a class="required file"
kevin
+1  A: 

You can't check that a submitted file is an image format at the client side, because the client side has no access to read the file.(*) That's why the plugin doesn't offer such a feature.

The only reliable check you can do on a file upload field to to check that its value is not an empty string (no file selected). Whilst you might be tempted to guess whether a file is an image by looking at the filename (eg. does it end in ‘.gif’, ‘.png’, ‘.jpeg’ or ‘.jpg’), this is unreliable as depending on the operating system and filetype configuration settings a file extension may well not bear any relation to the type of file.

(*: Except in Firefox 3 using the FileList interface.)

bobince
Agreed - and when you do actually upload the file, check the mime-type to ensure it's really a .jpg or whatever (and not a .php or .exe masquerading as one)
niggles
Thanks for the tip bobince. I finally managed with this code in the dom ready function:rules: { field: { required: true, accept: "xls|csv" } }
kevin
@niggles: check the contents of the file, not the MIME type. The MIME type submitted by the browser is very fragile as it depends on the OS's guesswork on what types files are. Very often you will get a misidentified Content-Type submission, or an unknown one, or just application/octet-stream.
bobince