title: Display image and Validation of image extension before uploading file Using Javascript
body: <p>My goal is to first validate the upload file is an image and if it is an image I will display it. I get the codes from <a href="https://stackoverflow.com/a/4237161/3188711">Validation Code</a> and <a href="https://stackoverflow.com/a/4459419/3188711">Image Code</a>.</p>
  
  <p>At first I was able to display image. However, when I combined display image code with validation code, I did not able to get both validation and display worked.</p>
  
  <p>Can anyone please help me? Below are my codes. Thanks in advance! :)</p>
  
  <pre><code>&lt;input type="file" name="dataFile" id="fileChooser" onchange="readURL(this);" /&gt;
  
  
  
  
  
  &lt;SCRIPT type="text/javascript"&gt;
  
  var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
  
       function readURL(input) {
  
           var arrInputs = document.getElementById("fileChooser").value;
              for (var i = 0; i &lt; arrInputs.length; i++) {
                  var oInput = arrInputs[i];
                  if (oInput.type == "file") {
                      var sFileName = oInput.value;
                  if (sFileName.length &gt; 0) {
                      var blnValid = false;
                      for (var j = 0; j &lt; _validFileExtensions.length; j++) {
                          var sCurExtension = _validFileExtensions[j];
                          if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                              blnValid = true;
  
                              if (input.files &amp;&amp; input.files[0])  {
                                  var reader = new FileReader();
  
                                  reader.onload = function (e) {
                                      $('#blah').attr('src', e.target.result)
                                  };
  
                                  reader.readAsDataURL(input.files[0]);
                              }
  
  
                              break;
                          }
                      }
  
                      if (!blnValid) {
                          alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                          return false;
                      }
                  }
              }
          }
  
          return true;
  
  
  
  
  
      }
  </code></pre>
  
  <p></p>