image validation in javascript – How to validate image file in JavaScript?

image validation in javascript – Filtering and validating file uploads with Javascript. how to check (validate) File (Image) size before upload using JavaScript and jQuery.

image validation in javascript

I will validate image file using JavaScript as well as allow user to select only .jpg, .jpeg, .png, and .gif type file.

File Type (extension) Validation with JavaScript

HTML code(index.html)

<!-- File input field -->
<input type="file" id="file" onchange="return checkAndFilterFiles()"/>

<!-- Image preview -->
<div id="imagePreview"></div>

JavaScript Code

function checkAndFilterFiles(){
    var userFileImg = document.getElementById('file');
    var destOrignalFile = userFileImg.value;
    var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
        alert('Please you can upload file having extensions .jpeg/.jpg/.png/.gif only.');
        userFileImg.value = '';
        return false;
        //Image displaying
        if (userFileImg.files && userFileImg.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = '<img src="''"/>';

Don’t Miss : Image Size Validation In Javascript Example

Also Read This πŸ‘‰   jQuery change class Examples with Demo

File Size Validation Using Javascript Example


<!DOCTYPE html>
<html lang="en">
    <title>File Size Validation Using Javascript Example -</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="">
<body class="bg-dark">
    <div class="continer">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <div class="card">
                    <div class="card-header">
                        <h5>File Size Validation Using Javascript Example</h5>
                    <div class="card-body">
                        <form method="post" name="frmAdd" id="frmAdd">
                            <label for="image">Image:</label>
                            <input type="file" name="image" class="form-control" id="image" value="" onchange="checkAndFilterFiles()"><br/>
                            <button type="submit" class="btn btn-success">Submit</button>        
<script type="Javascript">
    function checkAndFilterFiles() {
        var image = document.getElementById("image");
        if (typeof (image.files) != "undefined") {
            var size = parseFloat(image.files[0].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.");

I hope you get an idea about image validation in javascript.
I would like to have feedback on my
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.