In this blog post, we are going learn how to validate file type before uploading in React JS. Uploading files is a common task in many web applications. However, it’s important to ensure that the uploaded files are of the correct type to avoid errors.
In this tutorial, we will implement file type validation in React JS. We’ll create a simple component that allows users to select a file and checks that it’s one of the allowed file types (in this case, JPEG, PNG, or GIF images). And we will also handle form submission errors and display success and error messages to the user.
How to Check File Type in React JS
In the demo video above, we have a file input element and an upload button. When the user selects a file, we are checking whether the selected file is one of the allowed file types or not.
If the file type is not in the allowed type list, we will show an error message. If the selected file type is in the allowed type list, we will show a success message.
Step1: Defining state variables
const [file, setFile] = useState(null);
const [isError, setIsError] = useState(false)
const [errorMsg, setErrorMsg] = useState("");
const [isSuccess, setIsSuccess] = useState(false)
The `file`
state variable is used to store the selected file. The `isError`
state variable is used to determine whether an error occurred during file validation. The `errorMsg`
state variable is used to store the error message if an error occurred. The `isSuccess`
state variable is used to determine whether the file type is valid.
Step2: Using `handleFileChange` to check the selected file’s type
const handleFileChange = (event) => {
const selectedFile = event.target.files[0];
setIsSuccess(false);
// Checking if the file type is allowed or not
const allowedTypes = ["image/jpeg", "image/png", "image/gif"];
if (!allowedTypes.includes(selectedFile?.type)) {
setIsError(true);
setErrorMsg("Only JPEG, PNG, and GIF images are allowed.");
return;
}
setIsError(false);
setFile(selectedFile);
};
The `handleFileChange`
function is triggered when the user selects a file. The `selectedFile`
variable is used to store the selected file. Then we check whether the file type is allowed by comparing the selected file type with an array of allowed file types.
If the file type is not allowed, we set the `isError`
state variable to `true`
and display an error message. If the file type is allowed, we set the `isError`
state variable to `false`
and store the selected file in the `file`
state variable.
Step3: Preventing submission errors with handleSubmit
const handleSubmit = (event) => {
event.preventDefault();
if (isError) return;
setErrorMsg("");
// Checking if the file has been selected
if (!file) {
setIsError(true);
setErrorMsg("Please select a file.");
return;
}
setIsError(false);
setIsSuccess(true);
};
The `handleSubmit`
function is triggered when the form is submitted. We first prevent the default form submission behavior. If an error occurred during file validation, we return from the function.
If a file has not been selected, we set the `isError`
state variable to `true`
and display an error message. If a file has been selected, we set the ` isError`
state variable to `false`
and set the `isSuccess`
state variable to `true`
.
Step4: JSX code to render a form to select the file and validate
return (
<div className="container">
<div className="card">
<div className="card-header">
<h2 className="title">File Type Validation</h2>
</div>
<div className="card-body">
<form onSubmit={handleSubmit}>
<input
type="file"
onChange={handleFileChange}
/>
{isError && <div className="error-text">{errorMsg}</div>}
<button type="submit">Upload</button>
{isSuccess && <div className="success-text">Valid File Type</div>}
</form>
</div>
</div>
</div>
);
Finally, we return the JSX code that defines the form for selecting and validating the file. We display a card with a header and body, and within the body, we define a form with an input element for selecting a file.
We display the error message if an error occurred during validation, and we display a success message if the file type is valid.
Also, check out:
- How To Check Password Strength in React JS
- How to Check File Size in React
- Display CSV Data in a Table in React
Complete Code:
import React, { useState } from "react";
function App() {
const [file, setFile] = useState(null);
const [isError, setIsError] = useState(false)
const [errorMsg, setErrorMsg] = useState("");
const [isSuccess, setIsSuccess] = useState(false)
const handleFileChange = (event) => {
const selectedFile = event.target.files[0];
setIsSuccess(false)
// Checking if the file type is allowed or not
const allowedTypes = ["image/jpeg", "image/png", "image/gif"];
if (!allowedTypes.includes(selectedFile?.type)) {
setIsError(true)
setErrorMsg("Only JPEG, PNG, and GIF images are allowed.");
return;
}
setIsError(false)
setFile(selectedFile);
};
const handleSubmit = (event) => {
event.preventDefault();
if(isError) return
setErrorMsg("");
// Checking if the file has been selected
if (!file) {
setIsError(true)
setErrorMsg("Please select a file.");
return;
}
setIsError(false)
setIsSuccess(true)
};
return (
<div className="container">
<div className="card">
<div className="card-header">
<h2 className="title">File Type Validation</h2>
</div>
<div className="card-body">
<form onSubmit={handleSubmit}>
<input
type="file"
onChange={handleFileChange}
/>
{isError && <div className="error-text">{errorMsg}</div>}
<button type="submit">Upload</button>
{isSuccess && <div className="success-text">Valid File Type</div>}
</form>
</div>
</div>
</div>
);
}
export default App;
Output:
Conclusion
That’s it, we have implemented a file type validation in React. The `handleFileChange`
function checks if the file type is allowed, and the `handleSubmit`
function checks if a file has been selected and displays appropriate error messages. Finally, we display the form with the selected file and the error and success messages.