How to code image validation in JavaScript

by  
Share:
Image validation in JavaScript

Almost every project we use has an image/photo upload feature, and you must learn ways to perform image validation in JavaScript. In this tutorial, you will learn to write JavaScript validation for file upload extension and size.

View Demo

Learning Javascript FormData API

I have used FormData Web API to perfrom javascript validation for file upload extension and size. It is supported by all modern browsers.

The FormData API offers a way to conveniently construct a set of key/value pairs representing form fields and their values. It makes use of the very same format a form would likely use if the encoding type were set to “multipart/form-data”. You can learn more about FormData here.

Logic for Image validation in JavaScript

Let’s suppose you have a file field in a form, and you want to upload an image with client-side validation via JavaScript. It is crucial to validate forms at the client side to ensure that the user submits the correct input.

Let’s look at the approach to the problem below:

Firstly, Add the file element to the HTML/PHP page. Here’s the tag <input type="file" name="f" id="img" > Using ID attribute is important here.

You can also put the attribute accept="image/*" or accept="image/png,image/jpeg,image/bmp,image/gif" in the input field, and the user can only see the image type file when attaching the image.

Secondly, trigger a JavaScript function with onchange event. <input type="file" name="f" id="img" onchange="validateImage()" >

Finally, write the JavaScript function that handles all the validation logic.

The function validateImage() will return true only if the file of type JPG, JPEG, PNG, BMP, and GIF are attached.

Write code for Image validation in JavaScript

Here’s the code for single image validation in JavaScript. Make sure you add the ID attribute. A JavaScipt function validateImage() is been called on change event of the image field.

<input type="file" name="f" id="img" onchange="validateImage()" accept="image/png,image/jpeg,image/bmp,image/gif" >

The JavaScript code that will be called on change is given below.

<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;
	}

	return true;
}
</script>

Multiple image validation in JavaScript

As we have done the image validation for a single image field, we will do the same for the multiple image fields as well.

To give you an idea, let us take three file fields and validate them.

The ID for each file field has to be unique and passed as a parameter to the JavaScript function in change event.

<input type="file" name="f[]" id="img1" onchange="validateMultipleImage('img1')" accept="image/*" >
<input type="file" name="f[]" id="img2" onchange="validateMultipleImage('img2')" accept="image/*" >
<input type="file" name="f[]" id="img3" onchange="validateMultipleImage('img3')" accept="image/*" >

The JavaScript code that will be called to validate multiple image field is given below.

In case, you are wondering why the name attribute has an array or []. Read about uploading multiple files with PHP.

The function validateMultipleImage() accepts the ID of the file field and will return TRUE only if the file of type JPG, JPEG, PNG, BMP, and GIF is attached.

<script type="text/javascript">
function validateMultipleImage(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;
	}
}
</script>

File size validation in JavaScript

Additionally, if you prefer to write file size validation in JavaScript, this also is straightforward.

In this case, we will accept only JPG and PNG images with a maximum size of 2MB.

I have set to file size limit to 2MB, but you can adjust it to your preference.

Let us extend our JavaScript function validateImage() which we have written above, create a new one validateImageAndSize(), and add a few lines of codes that will help our cause.

Please Note: The upload file size is returned in bits, which we have to convert to MB for JavaScript check file size before upload.

<input type="file" name="f" id="fs" onchange="validateImageAndSize()" accept="image/*" >

The JavaScript function validateImageAndSize() is given below.

<script type="text/javascript">
function validateImageAndSize() {
	var formData = new FormData(); 
	var file = document.getElementById("fs").files[0]; 
	formData.append("Filedata", file);
	
	var t = file.type.split('/').pop().toLowerCase(); 
	if (t != "jpeg" && t != "jpg" && t != "png") {
		alert('Please select a valid image file');
		document.getElementById("fs").value = ''; 
		return false; 
	} 
	
	var fsize = (file.size / 1024 / 1024).toFixed(2); 
	if (fsize > 2 ) {
		alert('Max Upload size is 2MB only'); 
		document.getElementById("fs").value = ''; 
		return false; 
	} 
	return true;
}
</script>

View Demo

Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

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.