ReactJS file upload form validation

ReactJS file upload form validation

When working with file uploads in React, it's a good idea to add validation checks to make sure the uploaded file follows specific rules. Here's an example of a file upload form that checks the file type and size:

import React, { useState } from 'react';

const FileUploadForm = () => {
  const [selectedFile, setSelectedFile] = useState(null);
  const [fileErrors, setFileErrors] = useState('');

  const validateFile = (file) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    const maxSize = 5 * 1024 * 1024; // 5MB

    if (!allowedTypes.includes(file.type)) {
      return 'Invalid file type. Please upload a JPEG, PNG, or GIF file.';
    }

    if (file.size > maxSize) {
      return 'File size exceeds the maximum limit of 5MB.';
    }

    return null; // No errors
  };

  const handleFileChange = (event) => {
    const file = event.target.files[0];

    if (file) {
      const error = validateFile(file);
      if (error) {
        setFileErrors(error);
      } else {
        setFileErrors('');
        setSelectedFile(file);
      }
    }
  };

  const handleSubmit = (event) => {
    event.preventDefault();

    if (selectedFile) {
      // Perform file upload action (e.g., send file to server)
      console.log('File uploaded:', selectedFile);

      // Reset selected file and errors
      setSelectedFile(null);
      setFileErrors('');
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          Choose File:
          <input type="file" onChange={handleFileChange} />
        </label>
        {fileErrors && <p style={{ color: 'red' }}>{fileErrors}</p>}

        <button type="submit" disabled={!selectedFile}>
          Upload
        </button>
      </form>
    </div>
  );
};

export default FileUploadForm;

In this example,

In this example,

  1. The validateFile function looks at the chosen file's type and size, comparing them to set rules. Change the allowedTypes and maxSize variables based on what you need.

  2. The handleFileChange function starts when a file is picked. It uses validateFile and updates the component state.

  3. The handleSubmit function takes care of the form submission. It uploads the file if it's valid.

  4. The form button won't work until a valid file is chosen.

This example shows simple file type and size checks. You might need more advanced checks or use outside libraries for file checking in a real-world work setting. Also, think about adding server-side checks for better security.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!