File Validation using Pure JavaScript

Dec 03, 2022 · Article · 2 min, 447 words

Hi devs, I'll show you file size validation using pure JavaScript today. We often used it to validate our server-side code. That's good but not better. For seamless user experience, we should validate in real-time. So, let's see how we can easily integrate this using vanilla/pure JS.

File Size Validation

So, at first we'll see the below source code.

<!DOCTYPE html>
	<title>File size validation using Javascript -</title>
	<link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
<div class="container">
	<div class="row justify-content-center mt-5">
		<div class="col-md-8">
			<form enctype="multipart-formdata">
				<div class="form-group">
					<label for="image">Image</label>
					<input type="file" class="form-control" name="file" id="image" onchange="fileSizeVaklidation()">
  	function fileSizeValidation() {
        var image =[0];
        if (image) {
            var size = parseFloat(image.size / (1024 * 1024)).toFixed(2); 
            if(size > 2) {
                alert('Please select image size less than 2 MB');
        } else {
            alert("This browser does not support HTML5.");

Here what we do is, firstly we ran a onchange() event, so that when a user uploads a file we can execute our function called fileSizeValidation(). Where we give a condition like if a image size is below 2MB then it'll popup an alert saying "success" as below output we can see.

File Size under 2MB

But if a file size above 2MB then the below screen will be appears.

File Size above 2MB

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. 🙂


No comments yet…