Image size validation in javascript example

Image size validation in javascript example

JavaScript 28-07-2021 Saheb Sutradhar

Image size validation in javascript example

 

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

Image size validation in javascript example

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 user clicks the Upload button then uploadImage() 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 in image variable, defined an array with allowed image mime types and stored in allowedMimes variable , and the maxMb variable is holding the maximum allowed size (MB) of 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 the it will show the below message. 

Image size validation in javascript example

If image has value then the else block will get execute . Now in the else block first we have 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 in available in allowedMimes array or not  , if not it will display the below message .

Image size validation in javascript example

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 convert 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 grater than maxMb then display the below message.

Image size validation in javascript example

When the file pass all the validation Image has uploaded successfully :) message will be display . These are client side validation for image 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

 

Related Posts

Card image cap

Math Floor Javascript Method

JavaScript 16-07-2021 Saheb Sutradhar

math.floor javascript method takes a number type value as parameter and returns the round off of that value. The return value will be the nearest downward integ ...

Card image cap

Spread Operator in JavaScript

JavaScript 20-07-2021 Saheb Sutradhar

In this post we will learn what is spread operator in Javascript? How we can use it ? and Where we should use? Spread Operator allows you to spread out the ele ...

Card image cap

Remove duplicates from array in javascript

JavaScript 24-07-2021 Saheb Sutradhar

In this post i will show you how to remove duplicates from array in javascript.We can use filter() method to remove duplicates from array , if the index of the ...

Card image cap

Next and Previous Buttons in Javascript with Demo

JavaScript 27-07-2021 Saheb Sutradhar

In this post we will learn how to use next and previous buttons in javascript with demo application , the below example there is  image container and next, pre ...

Card image cap

How to get multiple checkbox value in javascript

JavaScript 30-07-2021 Saheb Sutradhar

In this post you will learn how to get multiple checkbox value in javascript . In many application you will find this kind of feature where we allow user to sel ...

Card image cap

Multiple checkbox validation in javascript

JavaScript 02-08-2021 Saheb Sutradhar

In your application you can use single check box or you can use multiple checkbox . Below examples will help you to understand multiple checkbox validation in j ...