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.
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.
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!
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With