开发者

Validate the uploaded file size with jQuery form validation remote method

I would like to do a filesize validation as follows. Please see whether this proposal method makes sense or not. This part alone should work.

1> After the user selects a file, I check whether the file has suffix as png, gif etc.
$("#myform").validate({
 rules: {
   fieldForUpload: {
     required: true,
     accept: "png|gif"
   }
 }
});

2> Then I would like to use aJax method to upload the file to server for validation even before the user clicks the submit button. http://docs.jquery.com/Plugins/Validation/Methods/remote#url

$("#myform").validate({
  rules: {
    fieldForUpload: {
      required: true,
      accept: "png|gif"
      remote: "check-filesize.php"
    }
  }
});

Here is my questions:

1> Is this method valid? In other words, can I validate the fieldUpload with "accept" + "remote" together?

2> Can I enforce to validate the "accept" first, then validate the "remote"?

3> How to implement this "remote" metho开发者_如何学God? FYI: I knew how to validate whether an email exists on the DB by using remote. Do I have to gain some different knowledge in order to achieve this?

Many thanks


If you want to use jQuery's validate you can by creating this method:

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 
});

You would use it:

$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});


Have you considered using a file upload widget? Normal form validation requires access to the form fields. It's not possible in most browsers to actually manipulate file upload input fields.

Check out Plupload and SWFUpload, two Flash-based file upload widgets that permit type and file size restrictions without sending the file to the server first.

There's also Ajax Upload and Uploadify, two jQuery plugins that try to use modern browser features to do the same thing. Older browsers might not have the same level of support.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜