Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

javascript - onchange jquery validation for file type

Here is my Fiddle

What i have is to display the image name near the upload text in the onchange event.

Here i need to have the validation on the onchange and it should display the error along with the file name

Here is what i have tried.

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

Note :

I don't want to do the validation in a seperate by setting rules, i want to do it in onchange, but it will be ok if i have the script inside the input type file code

Update : It will be better if i have the file name to be displayed and hide in 5 seconds, as i don't know to write script inside the input type file code

How can i do this, Help please

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<!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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...