Image validation into ReactJS

How to verify the image before uploading it into ReactJS. In this post, let’s validate the image file formats, Avoid invalid file formats for an image like MP4, or mp3 the application only should allow JPEG or PNG formats.

In an input form like any other input validation, image validation is also an important thing to implement. If a user uploads a file, without validating the type of that file, sometimes it may cause some errors or disturbance in data storing in the backend. Also, headers can upload the suspicious file.

Below are the steps to validate an image into ReactJS.

  • Setup the project environment
  • Create a form-type input field
  • Validate the file type

Setup the project environment

  • Open the ReactJS project folder and inside the src folder there, create another folder named, components.

  • Create a functional component inside the components folder.

import React from 'react';

const ImageValidation = () => {
    return (
        <div>

        </div>
    );
};

export default ImageValidation;
  • Import this functional component into App.js
// importing the functional component
import ImageValidation from "./components/ImageValidation";
import React from "react";
// importing the functional component
import ImageValidation from "./components/ImageValidation";

const App = () => {


  return (
    <div >
      <ImageValidation />
    </div>
  );
}

export default App

Create a “file-type” input field

  • Go to the newly created functional component and create an input field with file-type.
import React from 'react';

const ImageValidation = () => {
    return (
        <div>
            <input name="image" type="file" />
        </div>
    );
};

export default ImageValidation;

  • Add some styles to it so that it looks a little bit better.
import React from 'react';

const ImageValidation = () => {
    return (
        <div className="min-h-screen flex justify-center items-center">

            <form>
                <label class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300" for="file_input">Upload                    file</label>
                <input name="image" class="block w-full  text-gray-900 bg-gray-50 rounded-lg border border-gray-300 cursor-pointer dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="file_input" type="file" />
                <button type="submit" class="btn btn-sm px-4 my-5 block mx-auto">Submit</button>
            </form>


        </div>
    );
};

export default ImageValidation;

Note: We are using the Tailwind CSS component library to apply the styles. To know more about this, Read This Article.

Validate the file type in ReactJS

  • Add a onSubmit() handler to the form.
 <form onSubmit={handleImageSubmit}>
  • Get the file from the input with an event parameter of the handleImageSubmit function.
const image = e.target.image.value;
  • Check whether the input field is empty or if there is another file that is not an image.
if (!image) {
            setError('image is required');
            return false;
        } else {
            setError(null)
        }
        if (!image.match(/\.(jpg|jpeg|png|gif)$/)) {
            setError('select valid image.');
            return false;
        } else {
            setError(null)
        }
const handleImageSubmit = e => {
        e.preventDefault();
        const image = e.target.image.value;
        if (!image) {
            setError('image is required');
            return false;
        } else {
            setError(null)
        }
        if (!image.match(/\.(jpg|jpeg|png|gif)$/)) {
            setError('select valid image.');
            return false;
        } else {
            setError(null)
        }

 

  • Add a state which will hold the error message if the input field is empty or without any valid image.
const [error, setError] = useState(() => null)
const handleImageSubmit = e => {
        e.preventDefault();
        const image = e.target.image.value;
        if (!image) {
            setError('image is required');
            return false;
        }else{
        setError(null)
        }
        if (!image.match(/\.(jpg|jpeg|png|gif)$/)) {
            setError('select valid image.');
            return false;
        }else{
           setError(null)
        }

  • Add a conditional <p> tag inside the JSX which will show the error on the browser.
 {
                    error && <p className='text-error'>{error}</p>
 }
import React, { useState } from 'react';

const ImageValidation = () => {
    const [error, setError] = useState(() => null)
    const handleImageSubmit = e => {
        e.preventDefault();
        const image = e.target.image.value;
        if (!image) {
            setError('image is required');
            return false;
        }else{
         setError(null)
        }
        if (!image.match(/\.(jpg|jpeg|png|gif)$/)) {
            setError('select valid image.');
            return false;
        }else{
           setError(null)
        }

    }


    return (
        <div className="min-h-screen flex justify-center items-center">

            <form onSubmit={handleImageSubmit}>
                <label class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300" for="file_input">Upload file</label>
                <input name='image' class="block w-full  text-gray-900 bg-gray-50 rounded-lg border border-gray-300 cursor-pointer dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="file_input" type="file" />

                {
                    error && <p className='text-error'>{error}</p>
                }

                <button type='submit' class="btn btn-sm px-4 my-5 block mx-auto">Submit</button>
            </form>


        </div>
    );
};

export default ImageValidation;

As we can see, we are validating the file whether the value in it is an image or an empty field. There are many other ways to validate an image input field. This is one of those.