3

I know this may require some javascript but how can I tell the input inside my form to reject images with size different than 64 x 64 without pressing the submit button.

<div class="form-group">
   <label for="plat_img">Icono</label>
   <input type="file" 
          accept="image/*"
          class="form-control" 
          id="plat_img">

The verification should happen as soon as the image is selected and if rejected, notify the user via an alert.

3

2 Answers 2

5

This should do the job, you could now add a good error message as well.

var fileInput = document.getElementById("plat_img");
// listening on when someone selects a file
fileInput .onchange = function(e) {
  e.preventDefault();

  // get the file someone selected
  var file = fileInput.files && fileInput.files[0];

  // create an image element with that selected file
  var img = new Image();
  img.src = window.URL.createObjectURL(file);

  // as soon as the image has been loaded
  img.onload = function() {
    var width = img.naturalWidth,
      height = img.naturalHeight;

    // unload it
    window.URL.revokeObjectURL(img.src);

    // check its dimensions
    if (width <= 64 && height <= 64) {
      // it fits 
    } else {
      // it doesn't fit, unset the value 
      // post an error
      fileInput.value = ""
      alert("only 64x64 images")
    }
  };

};
Sign up to request clarification or add additional context in comments.

1 Comment

Explanation would be a nice addition instead of just dumping code. Just saying.
1

Since you're having a file there, you will first need to load it into an Image. After that, you can check the height and width to see if it fits your needs. Note that a server-side verification is necessary too, because JavaScript can be tricked. Browser support also varies.

1. Step: Handle `changed`-event
2. Step: Create Image, handle onload
3. Step: Load the file into the Image object

Demonstration: http://codepen.io/NikxDa/pen/apegZa

1 Comment

So whoever downvoted this could at least be kind enough to share the reason with me, so I can update the post accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.