Image File Extension Validation In jQuery

Image File Extension Validation In jQuery

Today in this series of jQuery validation you will learn about image validation. Image validation is a very important part of validation.

Image validation is an important part of web development. To upload an image, the value of the type attribute of the input field in the form is kept as "file". Also, an attribute is accepted and set whose value is given as "image". So that only the image is selected.

jQuery Validation

Image Validation

Validation of the image uploaded in the web is an important step, which ensures that the image uploaded by the developer is correct, in size and type. This prevents the wrong type of image being uploaded on the website. There are some common scenarios of validation, in which the image is checked at the time of uploading.

1. Checking the image document

First of all, it checks whether the image uploaded by the master is in the correct format, such as JPG, PNG, GIF, JPEG, BMP, WEBP, etc.
Scenario: If a motorcycle JPG image is being uploaded, but the website only has PNG or JPEG image status, then an error will pop up.

2. Checking the image size

The second validation is to ensure that the image size is not too large. This happens because if the image is too large, then the loading speed of the website may decrease.
Scenario: If any user is uploading an image of 20MB, but there is an image of only upto 5MB present on the website, then the validation will fail.

3. Checking the dimensions of the image

Sometimes specific dimensions of the image are required, such as width and width. This is especially true for phrase composition or banners.
Scenario: If you have designed a banner with an image of a width of 1200px and a width of 400px, then if the user uploads an image of 800px * 300px, then the validation can happen.

4. Checking the type of image

In any abstract, it is checked that the image does not contain any malicious content, such as any exact element or virus.
Scenario: If any user is uploading an abstract file (.exe) in the name of the image, then the validation should fail and he should be notified normally.

5. Checking for empty image file

Sometimes, the empty file may be uploaded by the user, or the image file may be stock. In this case, the image is checked to see whether it is valid or not.
Scenario: If the user tries to upload any image but is empty or blank, the file may fail.

6. Checking the mime type of the image

The mime type describes the actual content of the file. It is important to check whether the user who is uploading the file creates the image or not.
Scenario: If a user is uploading an essay (.pdf) or any other file, then after my checking it will throw an error.

Create The HTML Form Using Tailwind

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

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>RAYS CODING : Image Upload Validation</title>
        <link rel="stylesheet" href="../style.css">
        <script src="https://cdn.tailwindcss.com"></script>
    </head>

    <body class="bg-zinc-950 flex justify-center">
        <section class="w-auto h-auto mt-3 bg-white">
            <header class="bg-violet-600 p-5 pl-6 pr-6">
                <h2 class="text-3xl text-white tracking-wider">RAYS CODING : Image Upload Validation</h2>
            </header>
            <form action="#" method="post" class="p-6 max-w-lg mx-auto bg-white rounded-lg shadow-lg">

                <!-- Image Upload Section -->
                <label for="image" class="block text-xl font-semibold text-gray-700 mb-2 mt-2">Upload Image</label>

                <!-- Custom File Input Box -->
                <div class="relative">
                    <input type="file" name="image" id="image" class="hidden" accept="image/*" />
                    <label for="image"
                        class="flex items-center justify-center w-full px-4 py-2 bg-violet-600 text-white font-semibold cursor-pointer shadow-lg hover:bg-violet-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition duration-300">
                        <span>Choose an Image</span>
                    </label>
                </div>

                <!-- Image Preview Section -->
                <div id="image-preview" class="mt-5 hidden">
                    <p class="text-xl font-medium text-gray-700">Selected Image:</p>
                    <img id="image-display" src="" alt="Image Preview" class="w-full mt-3 h-52 rounded-md shadow-md" />
                    <p id="file-name" class="mt-2 text-gray-500"></p>
                </div>

                <!-- Message (Validation feedback) -->
                <div class="mt-5 bg-red-300 p-3 text-red-950 hidden" id="message"></div>

                <!-- Submit Button -->
                <button type="submit" id="submit-button" class="mt-5 bg-violet-600 p-2 w-full text-white font-semibold shadow-lg hover:bg-violet-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition duration-300">
                    Submit
                </button>
            </form>
        </section>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    </body>

    </html>
                 

This code creates the structure of a simple image upload form. It has a header, form, and image upload functionality. The form has a file input box, from which the user can select an image. When the image is selected, its preview is shown below.

jQuery Validation

When the image is selected, a preview area is activated which shows the preview of the image and the name of the file. If there is an error, a validation message is also shown. The submit button is used to submit the form, but this action is just a placeholder right now.

If jQuery is used in the code, it will be useful in the future to handle validation and dynamic changes.

Image Validation In jQuery

               
        <script>
            $(document).ready(function () {
                // Handle file selection
                $('#image').on('change', function () {
                    var file = this.files[0];
                    if (file) {
                        // Show the preview and file name
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            $('#image-display').attr('src', e.target.result);
                            $('#file-name').text(file.name);
                            $('#image-preview').removeClass('hidden');
                        };
                        reader.readAsDataURL(file);
                    }
                });
       
                // Handle form submission with extension and size validation
                $('#submit-button').on('click', function (e) {
                    e.preventDefault();
                    var imageFile = $('#image')[0].files.length;
       
                    // If no image is selected, show error message
                    if (imageFile === 0) {
                        e.preventDefault(); // Prevent form submission
                        $('#message').text('Please select an image before submitting.').removeClass('hidden');
                       
                        // Hide the message after 3 seconds
                        setTimeout(function() {
                            $('#message').addClass('hidden');
                        }, 3000); // 3000 milliseconds = 3 seconds
                       
                        return; // Exit the function if no file is selected
                    }
       
                    var file = $('#image')[0].files[0];
                    var fileName = file.name;
                    var fileExtension = fileName.split('.').pop().toLowerCase();
       
                    // List of allowed extensions
                    var allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
       
                    // Check if the selected file's extension is valid
                    if ($.inArray(fileExtension, allowedExtensions) === -1) {
                        e.preventDefault(); // Prevent form submission
                        $('#message').text('Invalid file type. Please select a JPG, JPEG, PNG, or GIF image.').removeClass('hidden');
                       
                        // Hide the message after 3 seconds
                        setTimeout(function() {
                            $('#message').addClass('hidden');
                        }, 3000); // 3000 milliseconds = 3 seconds
                       
                        return; // Exit the function if file type is invalid
                    }
       
                    // Check if the file size exceeds 1 MB (1,048,576 bytes)
                    var maxSize = 1048576; // 1 MB in bytes
                    if (file.size > maxSize) {
                        e.preventDefault(); // Prevent form submission
                        $('#message').text('File size exceeds the 1 MB limit. Please select a smaller image.').removeClass('hidden');
                       
                        // Hide the message after 3 seconds
                        setTimeout(function() {
                            $('#message').addClass('hidden');
                        }, 3000); // 3000 milliseconds = 3 seconds
                       
                        return; // Exit the function if file size is too large
                    }
       
                    // Optional: Clear the message if everything is valid
                    $('#message').addClass('hidden');
                });
            });
        </script>
                 

This script handles validation for image file upload and form submission. First, when the user selects a file, the #image input change event is triggered. Then, the preview of the image is shown using FileReader and the file name is also displayed.

jQuery Validation

After the form is submitted, the script checks if the image file is selected or not. If no file is selected, an error message is shown. After that, the extension and size of the selected file are validated. If the file type is invalid (for example, JPG, PNG) or the size is more than 1 MB, the form is not submitted and the user is shown the corresponding error message. If everything is correct, the message is hidden and the form is submitted.

Post a Comment

Previous Post Next Post

Recent in Technology