我是淘汰js的新手,并尝试使用knockout JS和文件API为客户端的文件输入编写自定义验证。主要目的是验证文件扩展名和文件大小,并在发生验证错误时清除文件输入路径。
以下是使用纯javascript完成的代码。感谢有人可以伸出援助之手。
function FileAPIViewModel() {
var self = this;
}
ko.applyBindings(new FileAPIViewModel());
$('#i_file').change( function() {
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
//get the file size and file type from file input field
var fsize = $('#i_file')[0].files[0].size;
var ftype = $('#i_file')[0].files[0].type;
if(fsize>10)
{
alert(fsize +" bites\nToo big!");
$('#i_file').val('');
}
switch(ftype)
{
case 'image/png':
case 'image/gif':
break;
default:
alert('Unsupported File!');
$('#i_file').val('');
}
}else{
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
<input type="file" input="" id="i_file" />
<input type="button" value="Submit" id="i_submit" />
答案 0 :(得分:1)
您可以尝试为此创建自定义jquery验证器。
$.validator.addMethod("filesize", function (value, element, params) {
//20000000
var ext = value.substr(value.length - 4);
//If there is no file
if (value === "") {
return false;
}
//check extension
if (ext !== null) {
if (ext !== ".pdf") {
return false;
}
}
//check file size
if(element.files[0] != null){
if (element.files[0].size > 20000000) {
return false;
}
}
return true;
}, 'Must Upload A Valid PDF Under 20MB');
然后将规则添加到您认为是i_file
的输入中$('[id^="i_file"]').each(function () {
$(this).rules('add', {
filesize: true
});
});