Image size validation in javascript example

By Saheb Sutradhar - Updated On 27-02-2024

Image size validation in javascript example

Image size validation in javascript example

 

In this article, you will learn Image size validation in javascript with examples, along with the size validation you will learn how to validate image mime type.

Copy the below code and save it in a file with .html extension and try by yourself 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image in javascript example</title>

    <style>
        .wrapper {
            text-align: center;
        }

        .submit-button {
            outline: none;
            padding: 12px;
            border: none;
            background-color: rgb(25, 121, 211);
            border-radius: 8px;
            color: white;
            cursor: pointer;
        }
    </style>
</head>

<body>

    <div class="wrapper">
        <h3>Image Upload Form</h3>

        <form name="imageUploadForm" onsubmit="uploadImage()" method="POST">
            <label for="image">Choose Image</label>
            <input type="file" name="select_image">
            <input type="submit" value="Upload" class="submit-button">
        </form>


    </div>

    <script>

        let image = document.forms['imageUploadForm']['select_image']; //fetched the input element and have stored in image variable.
        let allowedMimes = ['png', 'jpg', 'jpeg']; //allowed image mime types
        let maxMb = 2; //maximum allowed size (MB) of image

        function uploadImage() {
            if (!image.value) { // if the image input does not have value
                return showError('No image selected :(');
            }
            else {
                let mime = image.value.split('.').pop(); // get the extension/mime of image file
                if (!allowedMimes.includes(mime)) {  // if allowedMimes array does not have the extension
                    return showError("Only png,jpg,jpeg alowed");
                }
                else {
                    let kb = image.files[0].size / 1024; // convert the file size into byte to kb
                    let mb = kb / 1024; // convert kb to mb
                    if (mb > maxMb) { // if the file size is gratter than maxMb
                        return showError(`Image should be less than ${maxMb} MB`);
                    }
                    else { // if all the validations are good
                        alert("Image has uploaded successfully :)")
                    }
                }
            }
        }

        function showError(errorMessage) {
            alert(errorMessage);
        }

    </script>

</body>

</html>

 

In the above example first we have added a basic html file to upload the image. When the user clicks the Upload button then uploadImage() the function will get called.

<form name="imageUploadForm" onsubmit="uploadImage()" method="POST">
            <label for="image">Choose Image</label>
            <input type="file" name="select_image">
            <input type="submit" value="Upload" class="submit-button">
</form>

 

In the below code, I have fetched the input element and stored it in the image variable, defined an array with allowed image mime types and stored it in the allowedMimes variable, and the maxMb variable is holding the maximum allowed size (MB) of the image while upload. 

 

        let image = document.forms['imageUploadForm']['select_image']; //fetched the input element and have stored in image variable.
        let allowedMimes = ['png', 'jpg', 'jpeg']; //allowed image mime types
        let maxMb = 2; //maximum allowed size (MB) of image

 

In the below function first, we are checking if the image input has value or not if it does not have value then it will show the below message. 

No Image Selected :(

If the image has value then the else block will get executed. Now in the else block first we have to check the mime type of the image file by using this let mime = image.value.split('.').pop();  Once we have the file extension now check the extension is available in allowedMimes array or not  , if not it will display the below message .

Only png,jpg,jpeg allowed.

If the extension is available then it will go for the next image size validation , image.files[0].size  returns the size of the file in bytes, then converts the byte size into kb let kb = image.files[0].size / 1024; and now convert the kb to mb let mb = kb / 1024;  Now check if the mb value id greater than maxMb then display the below message.

Image Should be less than 2 MB.

When the file passes all the validation Image has uploaded successfully :) messages will be displayed. These are client-side validation for images in Javascript.

        function uploadImage() {
            if (!image.value) { // if the image input does not have value
                return showError('No image selected :(');
            }
            else {
                let mime = image.value.split('.').pop(); // get the extension/mime of image file
                if (!allowedMimes.includes(mime)) {  // if allowedMimes array does not have the extension
                    return showError("Only png,jpg,jpeg alowed");
                }
                else {
                    let kb = image.files[0].size / 1024; // convert the file size into byte to kb
                    let mb = kb / 1024; // convert kb to mb
                    if (mb > maxMb) { // if the file size is gratter than maxMb
                        return showError(`Image should be less than ${maxMb} MB`);
                    }
                    else { // if all the validations are good
                        alert("Image has uploaded successfully :)")
                    }
                }
            }

        }

 

 

I hope this article is helpful for you, I am very glad to help you thanks for reading

 

codelearningpoint © 2024