Validate single/ multiple image field using JavaScript

by  
Share:
Validate single/ multiple image

Image validation code is one of the most commonly used snippet. I have used this snippet on almost every project I worked on. So this time I thought to share this code with all of you. You can use this snippet to validate single/ multiple image field using JavaScript on any project you like.

Steps to validate image field using JavaScript

It’s a two steps process,

  1. Add input field (file type) in your php, html, asp file.
  2. Write JavaScript code to validate that image field. and bind the validation to an event (I have used onchange event to trigger the validation code).

Note: I have used FormData API to validate, it supports on all modern browser but not on old browser. You can see the latest wiki info here.

Validate single image field using JavaScript

Add image field code in your html, php,  asp file.

<!-- Give and ID to this field and bind it with the javascript function. -->
<!-- Bind the function onchange event -->
<input type="file" name="f" id="img" onchange="validateImage()" >

Once you are done with the above, create a JavaScript function validateImage() you can name this function according to your preference. When validating you should check the image type and image size to keep up a limit. In my code I will check image of jpeg, jpg, png, bmp, and gif types only. Also the maximum upload image size is 1MB.
<script type="text/javascript">
function validateImage() {
    var formData = new FormData();

    var file = document.getElementById("img").files[0];

    formData.append("Filedata", file);
    var t = file.type.split('/').pop().toLowerCase();
    if (t != "jpeg" && t != "jpg" && t != "png" && t != "bmp" && t != "gif") {
        alert('Please select a valid image file');
        document.getElementById("img").value = '';
        return false;
    }
    if (file.size > 1024000) {
        alert('Max Upload size is 1MB only');
        document.getElementById("img").value = '';
        return false;
    }
    return true;
}
</script>

Additionally you can also put this attribute ‘accept=”image/*”‘ in the input field, so user can only see file of image type file when uploading the image from their system.
<input type="file" name="f" accept="image/*" id="img" onchange="validateImage()"  >

Validate multiple image field using JavaScript

I would like to recommend that first of all you try validate single image and check if that is working perfectly then move on with this multiple image field validation.

In this section you can validate multiple image field, first of all create 3 image fields ( you can create many) and assign each one of them with a unique ID, then bind them on onchange event with a JavaScript function and pass the unique ID as a parameter in the function.

<!-- Assign unique ID to each and pass the same ID as a parameter -->
<input type="file" name="f[]" id="img1" onchange="validateImage('img1')" >
<input type="file" name="f[]" id="img2" onchange="validateImage('img2')" >
<input type="file" name="f[]" id="img3" onchange="validateImage('img3')" >

Customize the javascript validation function that we wrote before. Everything will be same except the ID will be dynamic now and will be passed as a parameter.
<script type="text/javascript">
function validateImage(id) {
    var formData = new FormData();

    var file = document.getElementById(id).files[0];

    formData.append("Filedata", file);
    var t = file.type.split('/').pop().toLowerCase();
    if (t != "jpeg" && t != "jpg" && t != "png" && t != "bmp" && t != "gif") {
        alert('Please select a valid image file');
        document.getElementById(id).value = '';
        return false;
    }
    if (file.size > 1024000) {
        alert('Max Upload size is 1MB only');
        document.getElementById(id).value = '';
        return false;
    }
    return true;
}
</script>

If you know any better technique to validate the image fields please do share with us.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Divesh on

Thanks the code is working but in case of multiple image having sane id and class like the form below than how can do this with onchange

Reply
Shahrukh Khan on

just call the same function onchange.

Reply
nithish on

how to validate image multiple image size before upload

Reply
Shahrukh Khan on

image dimension or physical size?

Reply
Arjun R on

In case single image or multiple img tags with same id it is working. But one thing you missed is img with multiple attribute.

Reply
Arjun R on

And here the code multiple attribute in img tag.

function validateImages(id) {
var formData = new FormData();
var files = document.getElementById(id).files;
var check = true;
for(var i=0;i 1024000) {
alert(‘Max Upload size is 1MB only’);
document.getElementById(id).value = ”;
check = false;
return false;
}
}
return check;
}

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.