Image File Extension Validation In jQuery

Image File Extension Validation In jQuery

Welcome to the sixth article of our jQuery validation series! In this article, I'll give you practical knowledge of "how to validate image file extensions using jQuery".  This "validation" is the most important for web developers.  So it's important for you.

Image File Extension Validation In jQuery

Step of Name Validation

  1. Create an HTML form
  2. Write the validation code

Create an HTML form

<!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>Rays Coding-JQuery Validation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container mt-5 form_box">
        <div class="row">
            <div class="card p-0">
                <div class="card-header bg-primary">
                    <h3 class="text-center text-white">Rays Coding :- JQuery Form Validation(Image)</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-lg-12">
                            <h5>Upload Your Profile</h5>
                        </div>
                        <div class="col-lg-12">
                            <form action="#" method="post" enctype="multipart/form-data">
                                <div class="row check_id">
                                    <div class="col-lg-6">
                                        <input class="form-control" type="file" name="userprofilfe" id="user_profile">
                                        <img src="" alt="" class="profile_preview">
                                    </div>
                                    <span id="userprofilfe_error" class="userprofilf_error"></span>
                                </div>
                                <div class="row">
                                    <div class="col-lg-4">
                                        <button type="submit" class="btn btn-primary mt-4" name="sub_btn" id="sub_button">Submit</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-lg-12 validationtext">
                <h1>jQuery Image Validation</h1>
            </div>
        </div>
    </div>
    <!-- jquery  CDN -->
    <script src="https://code.jquery.com/jquery-3.6.2.slim.min.js" integrity="sha256-E3P3OaTZH+HlEM7f1gdAT3lHAn4nWBZXuYe89DFg2d0=" crossorigin="anonymous"></script>
</body>
</html>

This HTML code presents a webpage intended for form validation using jQuery, with a specific focus on validating image uploads. The structure of the webpage is established using HTML elements with Bootstrap CSS classes for styling.

The main content resides within a container with the class "container". Inside it, a card layout is implemented using Bootstrap classes, featuring a header and a body section.

The header of the card displays the title "Rays Coding:- JQuery Form Validation(Image)" in a visually prominent manner, indicating the purpose of the form validation, which is to handle image uploads.

Moving to the body section, there's a heading "Upload Your Profile" followed by a form element. This form is configured to handle file uploads (enctype="multipart/form-data") and contains an input field of type "file" () with the ID "user_profile" for selecting a profile image. Additionally, there's an empty element with the class "profile_preview" meant for displaying a preview of the selected image.

An element with the ID "userprofilfe_error" is placed after the file input field. This span will be utilized to display error messages related to image upload validation.

Below the form, there's a submit button styled using Bootstrap classes, allowing users to submit the form.

Further down the webpage, outside the card container, there's a separate section with the heading "jQuery Image Validation". This section appears to provide additional context or instructions related to the image upload validation process.

Lastly, the page includes a script tag importing jQuery from a content delivery network (CDN). This jQuery script will likely be used to implement the image upload validation logic, although the validation script itself is not provided in the given code snippet.

Write the validation code

<script>
    $(document).ready(function () {
        $('#sub_button').on('click', function () {
            var field_val = $('#user_profile').val();                
            var extension_arr = ['jpeg', 'jpg', 'png'];
            var img_exte = field_val.split('.').pop();
            var serach_exte = extension_arr.includes(img_exte);
            if (field_val == '')
            {
                $('#userprofilfe_error').text('Please Upload Profile Image.');
                $('#userprofilfe_error').css('color', 'red');
                $('#user_profile').focus();
                return false;
            }
            else if (!serach_exte)
            {
                $('#userprofilfe_error').text('Please  Upload Image In jpg, jpeg, png format.');
                $('#userprofilfe_error').css('color', 'red');
                $('#user_profile').focus();
                return false;
            }
        });
    })
</script>

Image File Extension Validation In jQuery

This JavaScript code is designed to handle form validation for image uploads using jQuery. It's triggered when the submit button with the ID "sub_button" is clicked and executes within the $(document).ready() function, ensuring all DOM elements are loaded before executing.

First, it retrieves the value of the file input field with the ID "user_profile" using jQuery's .val() method and stores it in the variable field_val. This value typically represents the path or name of the uploaded file.

Image-File-Extension-Validation-In-jQuery

Next, it initializes an array called extension_arr containing valid image file extensions such as 'jpeg', 'jpg', and 'png'. Then, it extracts the extension of the uploaded file by splitting field_val using the period ('.') as a delimiter and fetching the last element of the resulting array, storing it in img_exte.

After that, it checks if field_val is empty. If it is, indicating no file has been selected for upload, it sets the error message to "Please Upload Profile Image.", changes its color to red, focuses on the file input field, and returns false to prevent form submission.

If the file input is not empty, it proceeds to check if the file extension is included in the extension_arr. If the extension is not found in the array, indicating an invalid file format, it sets the error message to "Please Upload Image In jpg, jpeg, png format.", changes its color to red, focuses on the file input field, and returns false to prevent form submission.

Post a Comment

Previous Post Next Post

Recent in Technology