1

I'm trying to validate the image before being uploaded. I restrict the size and pixels but the problem is that I can still upload the image even though it doesn't apply to the restrictions. How can I stop the user or disable the upload as this validation is done with the onchange command.

var myFile = document.getElementById('file');

myFile.addEventListener('change', function() {
  image = new Image();

  if(this.files[0].size > 800000)
  {
        alert("File size too big. Please upload a smaller image");
        return false;
  }
  else
  {
    var reader = new FileReader();
         //Read the contents of Image File.
    reader.readAsDataURL(this.files[0]);
    reader.onload = function (e) 
    {
        //Initiate the JavaScript Image object.
        var image = new Image();
        //Set the Base64 string return from FileReader as source.
        image.src = e.target.result;
        image.onload = function () {
            //Determine the Height and Width.
            var height = this.height;
            var width = this.width;
            if (height > 500 || width > 375) {
                alert("Height and Width must not exceed 500px(h) and 375px(w).");
                return false;
            }
            else
            {
               alert("Uploaded image has valid Height and Width.");
               return true;
            }
        };
    }
  }


});
Muppet
  • 356
  • 1
  • 4
  • 14

2 Answers2

0

You can reset the value of the file input element if your validation fails

var myFile = document.getElementById('file');
...
myFile.value=""

And then show validation to the user in page.

George Lee
  • 826
  • 6
  • 11
0

Here's what I did as an alternative. I didn't know this was possible until I came upon this. You just add this to the relevant alert/return false section and it disables the submit button.

jQuery("input[type='submit']").attr("disabled", 'disabled');
Muppet
  • 356
  • 1
  • 4
  • 14
  • It is advisable to use the jQuery [`prop(..)`](http://api.jquery.com/prop) function instead e.g. jQuery("input[type='submit']").prop("disabled", true) – George Lee Nov 17 '15 at 10:13
  • can you maybe give a short feedback answer as to why? I'm Interested to know as I'm not too clued up about it – Muppet Nov 17 '15 at 10:22
  • This has been covered in another [post](http://stackoverflow.com/questions/5874652/prop-vs-attr) which goes in to some good detail about the differences. Hope that helps. – George Lee Nov 17 '15 at 10:26