Does anyone know how can I validate a file input to only accept .zip
files with parsley.js?
I have looked around but I can not see how to do this.
Does anyone know how can I validate a file input to only accept .zip
files with parsley.js?
I have looked around but I can not see how to do this.
You can do that with a custom validator that validates the extension of the provided file path and check if it's zip
. Something like this (check this jsfiddle):
<form id="myForm">
<input type="file" name="some-file" data-parsley-fileextension='zip' />
<input type="submit" />
</form>
<script>
$(document).ready(function() {
window.ParsleyValidator
.addValidator('fileextension', function (value, requirement) {
// the value contains the file path, so we can pop the extension
var fileExtension = value.split('.').pop();
return fileExtension === requirement;
}, 32)
.addMessage('en', 'fileextension', 'The extension doesn\'t match the required');
$("#myForm").parsley();
});
</script>
Note that we set the attribute data-parsley-fileextension='zip'
on the input in order to know which extension must be provided. On the custom validator (which I named fileextension
) you have to take the extension from the file path and check if it matches the one you want.
You can check this answer to find ways to get the extension from a file path in javascript.
If you need to validate multiple extensions, you just have to tweak this solution a bit.