How to Validate a Date in ReactJS?
Last Updated : 01 Oct, 2024
Validating input Date in react ensures the correct date input. The valid date input is commonly used in case of calculating days, getting DOB for user data, and other operations etc.
Prerequisites:
Approach
To validate a date in React we will use the validator npm package. Take the date input from users and validate the input using validator.isDate() function. This function returns boolean value. Display the message "Valid Date" if it gives true else return the message "Enter Valid date".
import validator from "validator";
const validateDate = (value) => {
if (validator.isDate(value)) {
return "Valid Date :)";
} else {
return "Enter Valid Date!";
}
};
Step to Create React App and Install Module
Step 1: Create a React application using the following command:
npx create-react-app datevalidatedemo
Step 2: After creating your project folder i.e. datevalidatedemo, move to it using the following command:
cd datevalidatedemo
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure:
Project StructureThe updated dependencies in the package.json file are:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"validator": "^13.12.0",
"web-vitals": "^2.1.4"
},
Example: This example uses the validator npm package to validate date in React app.
JavaScript import React, { useState } from "react"; import validator from "validator"; const App = () => { const [errorMessage, setErrorMessage] = useState(""); const validateDate = (value) => { // Check if the input has at least 10 characters (e.g., "YYYY-MM-DD") if (value.length === 10) { // Validate date using validator's isDate function if ( validator.isDate(value, { format: "YYYY-MM-DD", strictMode: true }) ) { setErrorMessage("Valid Date :)"); } else { setErrorMessage("Enter Valid Date! Use format YYYY-MM-DD."); } } else { setErrorMessage("Enter Valid Date! Use format YYYY-MM-DD."); } }; return ( <div style={{ marginLeft: "200px" }}> <h2>Validating Date in ReactJS</h2> <div> <span>Enter Date (YYYY-MM-DD): </span> <input type="text" onChange={(e) => validateDate(e.target.value)} placeholder="YYYY-MM-DD" /> </div> <br /> <span style={{ fontWeight: "bold", color: "red" }}> {errorMessage} </span> </div> ); }; export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: