簡體   English   中英

文件類型的onchange jQuery驗證

[英]onchange jquery validation for file type

這是我的小提琴

我所需要的是在onchange事件中在上傳文本附近顯示圖像名稱。

在這里,我需要對onchange進行驗證,它應該顯示錯誤以及文件名

這是我嘗試過的。

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

注意 :

我不想通過設置規則來單獨進行驗證,我想在onc​​hange中進行驗證,但是如果我在輸入類型文件代碼中包含腳本,也可以

更新:如果我要在5秒內顯示和隱藏文件名,那會更好,因為我不知道在輸入類型文件代碼中編寫腳本

我該怎么辦,請幫忙

<!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>

使用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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM