结合文件大小检查和文件类型检查 - JS验证

时间:2016-03-13 11:20:45

标签: javascript jquery validation

所以我试图在文件本身上传之前验证文件上传,并且想要检查两个条件 - 文件是否小于5mb以及文件是否是图像格式。

这就是我现在正在做的事情:

<script>
$(document).ready(function () {
  $('input[type=file]').change(function () {
    var fileSize = this.files[0].size/1024/1024;
    if (fileSize > 5) { alert("Please check the size of your image");
      $(this).val('');
    }
    var val = $(this).val().toLowerCase();
    var regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$");
    if(!(regex.test(val))) {
      $(this).val('');
      alert('Only image files are supported. Please check the format of your file and try again.');
    } 
  }); 
});
</script>

它工作正常,但如果文件太大而被删除,则错误文件类型的警报也会因为输入已更改而触发。

有没有更好的办法解决这个问题?我想检查这两个条件,如果只有图像大小错误,用户不会收到有关文件格式的警告。如果第一个功能被触发,我可以杀掉第二个功能吗?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作,创建和管理一系列错误,并在最后使用它。单击“运行”以查看演示

$(document).ready(function() {
  $('input[type=file]').change(function() {
    var file = this.files[0],
        val = $(this).val().trim().toLowerCase();
    if (!file || $(this).val() === "") { return; }
    
    var fileSize = file.size / 1024 / 1024,
        regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$"),
        errors = [];
    
    if (fileSize > 5) {
      errors.push("Please check the size of your image");
    }
    if (!(regex.test(val))) {
      errors.push('Only image files are supported. Please check the format of your file and try again.');
    }
    if (errors.length > 0) {  
      $(this).val('');
      alert(errors.join('\r\n'));
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />

相关问题