简体   繁体   English

使用敲除JS和文件API进行输入文件验证

[英]Input file validation with knockout JS and file API

I am new to knockout js and trying to write custom validation for file input from client side using knockout JS and file API. 我是敲除JS的新手,并尝试使用敲除JS和文件API为来自客户端的文件输入编写自定义验证。 The main aim is to validate the file extension and file size, and clear the file input path should validation error occur. 主要目的是验证文件扩展名和文件大小,并在发生验证错误时清除文件输入路径。

Below is the code being done using pure javascript. 下面是使用纯JavaScript完成的代码。 Appreciate if someone could lend a hand. 欣赏是否有人可以伸出援手。

 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" /> 

You could try making a custom jquery validator for this. 您可以尝试为此创建一个自定义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');

Then add rule to your input(s) which I believe is i_file 然后将规则添加到您认为是i_file的输入中

$('[id^="i_file"]').each(function () {

    $(this).rules('add', {

        filesize: true

    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM