Does anyone know how can I validate a file input to only accept .zip
files with parsley.js?
有谁知道如何验证文件输入只接受parsley.js的.zip文件?
I have looked around but I can not see how to do this.
我环顾四周,但我看不出怎么做。
1 个解决方案
#1
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):
您可以使用自定义验证程序来验证提供的文件路径的扩展名并检查它是否为zip。像这样的东西(检查这个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.
请注意,我们在输入上设置属性data-parsley-fileextension ='zip',以便知道必须提供哪个扩展名。在自定义验证器(我将其命名为fileextension)上,您必须从文件路径中获取扩展名,并检查它是否与您想要的扩展名匹配。
You can check this answer to find ways to get the extension from a file path in javascript.
您可以查看此答案,以找到从javascript中的文件路径获取扩展名的方法。
If you need to validate multiple extensions, you just have to tweak this solution a bit.
如果您需要验证多个扩展,则只需稍微调整此解决方案即可。
#1
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):
您可以使用自定义验证程序来验证提供的文件路径的扩展名并检查它是否为zip。像这样的东西(检查这个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.
请注意,我们在输入上设置属性data-parsley-fileextension ='zip',以便知道必须提供哪个扩展名。在自定义验证器(我将其命名为fileextension)上,您必须从文件路径中获取扩展名,并检查它是否与您想要的扩展名匹配。
You can check this answer to find ways to get the extension from a file path in javascript.
您可以查看此答案,以找到从javascript中的文件路径获取扩展名的方法。
If you need to validate multiple extensions, you just have to tweak this solution a bit.
如果您需要验证多个扩展,则只需稍微调整此解决方案即可。