Validate file extension and size before submitting form

后端 未结 7 1531
無奈伤痛
無奈伤痛 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:41

    Be aware that element.files[0].size works with byte unit. So if you want to work with MB, you need to convert it to bytes. In this example:

    $.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');
    

    You need to pass into your validate:

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

提交回复
热议问题