Validate file extension and size before submitting form

后端 未结 7 1533
無奈伤痛
無奈伤痛 2020-12-30 06:51

I am using jQuery validate plugin, and want to validate file extension and file size before submitting a form.

\"use strict\";
$(\'#update_profile\').validat         


        
相关标签:
7条回答
  • 2020-12-30 07:47

    You need to write a custom rule to validate file size, also the file extensions has to be passed as a comma separated string

    $.validator.addMethod('filesize', function (value, element, param) {
        return this.optional(element) || (element.files[0].size <= param)
    }, 'File size must be less than {0}');
    
    jQuery(function ($) {
        "use strict";
        $('#update_profile').validate({
            rules: {
                FirstName: {
                    required: true,
                    maxlength: 20
                },
                image: {
                    required: true,
                    extension: "jpg,jpeg",
                    filesize: 5,
                }
            },
        });
    });
    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
    
    <form id="update_profile" method="post" action="">
      <input type="file" name="image" />
      <input type="submit" value="Save" />
    </form>

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