Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate file extension and size before submitting form

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

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

I want code similar to the above.

like image 691
Mahesh Jagdale Avatar asked Oct 13 '15 07:10

Mahesh Jagdale


People also ask

How do I validate file extensions?

Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.

Should you just check to file extension to ensure correct file type upload?

There's no error checking on these to keep them short, presumably if you use them you'll make sure the input exists first and the extensions array is valid!

What is file upload validation?

File Extension Validation This is basically where you are checking the extension of the presented file and making sure it is one that you should be accepting. This check is non-trivial, as there are multiple ways to evade this filtering depending on how you are implementing it.


1 Answers

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>
like image 143
Arun P Johny Avatar answered Nov 29 '22 13:11

Arun P Johny