onchange jquery 对文件类型的验证

onchange jquery validation for file type

本文关键字:验证 类型 文件 jquery onchange      更新时间:2023-09-26

这是我的小提琴

我所拥有的是在onchange事件中的上传文本附近显示图像名称。

在这里,我需要对onchange进行验证,它应该显示错误以及文件名

这是我尝试过的。

Upload<input type="file" onchange=" document.getElementById('spanFileName').innerHTML = this.value;" style="display:block;margin-top: -20px;opacity: 0;" >

注意:

我不想通过设置规则单独进行验证,我想在 onchange 中进行验证,但是如果我在输入类型文件代码中有脚本就可以

更新:如果我有要在 5 秒内显示和隐藏的文件名会更好,因为我不知道在输入类型文件代码中编写脚本

我该怎么做,请帮忙

使用 JQuery 的解决方案非常简单

将您的 HTML 作为

Upload<input type="file" id="fileUpload" style="display:block;margin-top: -20px;opacity: 0;" >
<span id='spanFileName'></span>

然后使用 Jquery

$('#fileUpload').on("change",function () {
                var fileExtension = ['jpeg', 'jpg'];
                if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                    // alert("Only '.jpeg','.jpg' formats are allowed.");
                    $('#spanFileName').html(this.value);
                    $('#spanFileName').html("Only '.jpeg','.jpg' formats are allowed.");
                }
                else {
                    $('#spanFileName').html(this.value);
                   //do what ever you want
                } 
 }) 

这是工作示例 http://jsfiddle.net/c9sbmdv5/3/

<!doctype html>
<html lang="en">    
<head>
  <meta charset="utf-8">
  <title>Validation</title>
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>  
  <style type="text/css">
  label input[type="file"] 
{
display: block;
margin-top: -20px;
opacity: 0;
}
  </style>
  <script>
   $(window).ready(function() {
$(document).delegate('#Upload','change',function(){
  var s=$(this).val();
  function stringEndsWithValidExtension(stringToCheck, acceptableExtensionsArray, required) {
    if (required == false && stringToCheck.length == 0) { return true; }
    for (var i = 0; i < acceptableExtensionsArray.length; i++) {
        if (stringToCheck.toLowerCase().endsWith(acceptableExtensionsArray[i].toLowerCase())) { return true; }
    }
    return false;
}
$('#spanFileName').html(s);
setTimeout(function(){
  $('#spanFileName').html("");
},15000)
String.prototype.startsWith = function (str) { return (this.match("^" + str) == str) }
String.prototype.endsWith = function (str) { return (this.match(str + "$") == str) }
  alert(s);
   if (!stringEndsWithValidExtension($("[id*='Upload']").val(), [".png", ".jpeg", ".jpg", ".bmp"], false)) {
        alert("Photo only allows file types of PNG, JPG and BMP.");
        return false;
    }
    return true;
});
});
  </script>
</head>
<body>
Upload<input id='Upload' type="file" style="display:block;margin-top: -20px;opacity: 0;" >
<span id='spanFileName'></span>
</body>
</html>