jQuery Validate File Upload

前端 未结 1 1374
不思量自难忘°
不思量自难忘° 2021-01-30 07:08

I am trying to validate a HTML file upload using jQuery Validate

I found I can use the meta option like:

$(\"#myform\").validate({
   meta: \"validate\"         


        
1条回答
  •  难免孤独
    2021-01-30 08:07

    If you want to use jQuery's validate to check the size of the file, you can do so by doing the following :

    1- load the additional methods file

    
    

    2- add a custom method to validate the file size

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

    3- use the newly added method as a validation rule to validate your input:

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

    Note: using the "accept" validation rule instead of "extension" result in MIME type error messages when you upload a file with a blank file type.

    0 讨论(0)
提交回复
热议问题