在提交表单之前验证文件扩展名和大小

时间:2015-10-13 07:26:56

标签: jquery jquery-validate

我正在使用jQuery validate插件,并希望在提交表单之前验证文件扩展名和文件大小。

"use strict";
$('#update_profile').validate({
    rules: {
        FirstName: {
            required: true,
            maxlength: 20
        },
        image: {
            required: true,
            extension: "jep | jpeg",
            filesize : 50000,
        }
    }
});

我想要与上面类似的代码。

7 个答案:

答案 0 :(得分:25)

您需要编写自定义规则来验证文件大小,文件扩展名也必须以逗号分隔的字符串传递



$.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,
            }
        },
    });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$.validator.addMethod('filesize', function (value, element, arg) {
            var minsize=1000; // min 1kb
            if((value>minsize)&&(value<=arg)){
                return true;
            }else{
                return false;
            }
        });

        $("#myform" ).validate({
            rules: {
                file_upload:{
                    required:true,
                    accept:"application/pdf,image/jpeg,image/png",
                    filesize: 200000   //max size 200 kb
                }
            },messages: {
                file_upload:{
                    filesize:" file size must be less than 200 KB.",
                    accept:"Please upload .jpg or .png or .pdf file of notice.",
                    required:"Please upload file."
                }
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

最小1 kb到最大200 kb文件大小并经过测试

答案 2 :(得分:1)

phpinfo
$.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,
            }
        },
    });
});

答案 3 :(得分:0)

如果您使用的是additional-methods.js,则可以这样操作:

$('#update_profile').validate({
    rules: {
        FirstName: {
            required: true,
            maxlength: 20
        },
        image: {
            required: true,
            extension: "jep | jpeg",
            maxsize: 50000,
        }
    }
});

答案 4 :(得分:0)

请注意element.files [0] .size使用字节单位。因此,如果要使用MB,则需要将其转换为字节。在此示例中:

$.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param * 1000000)
}, 'File size must be less than {0} MB');

您需要通过验证:

$('#update_profile').validate({
    rules: {
        FirstName: {
            required: true,
            maxlength: 20
        },
        image: {
            required: true,
            extension: "jep | jpeg",
            filesize : 5, // here we are working with MB
        }
    }
});

答案 5 :(得分:-1)

 HTML


                <div class="col-sm-9 col-lg-6 col-xs-12 col-md-9">
                    <div class="input-group">
                        <input type="text" class="form-control"  name="uploadFile"  readonly id="uploadFile">
                        <span class="input-group-btn">
                            <span class="btn btn-primary btn-file">
                                Browse&hellip;  <input type="file" id="uploadFile" name="uploadFile" >         
                            </span>
                        </span>
                    </div>
                    <div id="spanUploadFile">

//Message will display here
                    </div>

                </div>


JQuery



 $(document).on('change', '.btn-file :file', function() {

        var input = $(this),numFiles = input.get(0).files ? input.get(0).files.length : 1,
                label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
        var msg = "spanUploadFile";
        input.trigger('fileselect', [numFiles, label]);
        genrateFileMsg(this.id, msg)
genrateSizeMsg(this.files[0], msg)


    });

 function genrateFileMsg(id, nId)
    {

        var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
        var fileExtensionDOB = ['pdf'];
        //var fileExtensionDOB = ['pdf', 'doc', 'docx', 'txt', ];

            if ($.inArray($("#" + id).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                $("#" + nId).html("Only files of type jpg, png, gif, jpeg is allowed");

                return false;
            }







        return true
    }
    function genrateSizeMsg(f, nId)
    {

        var f = f.size;


            f = f / 1024;

            if (f > 100)
            {
                $("#" + nId).html("The file you are trying to upload is too large (max 100KB)");
                return false;
            }



        return true;
    }

答案 6 :(得分:-1)

<!-- Size in kb -->
   $.validator.addMethod('filesize', function (value, element,param) {
   
  var size=element.files[0].size;
 
  size=size/1024;
  size=Math.round(size);
  return this.optional(element) || 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: 1000
            }
        },
    });
});
<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>

最大大小1000kb