Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to validate URL in ReactJS?
Next article icon

How to Validate a Date in ReactJS?

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • React JS
  • Node JS and NPM

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 Structure

The 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:

Output-date-validation-in-react


Next Article
How to validate URL in ReactJS?
author
gouravhammad
Improve
Article Tags :
  • JavaScript
  • ReactJS
  • Technical Scripter
  • Web Technologies

Similar Reads

  • How to Validate an Email in ReactJS ?
    Validating email in React is an important step to authenticate user email. It ensures the properly formatted email input from the user. The following example shows how to validate the user entered email and checking whether it is valid or not using the npm module in React Application. ApproachTo val
    2 min read
  • How to validate URL in ReactJS?
    URL (Uniform Resource Locator) is a reference/address to a resource on the Internet. For example, www.geeksforgeeks.com is a URL. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application.  Creating React Ap
    2 min read
  • How to Validate Octal number in ReactJS?
    The Octal numeral system is the base-8 number system which uses the digits 0 to 7. It is also known as Oct for short. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application. ApproachTo validate octal numb
    2 min read
  • How to apply validation on Props in ReactJS ?
    Need of Validating Props in React JS Props are used to pass the read-only attributes to React components. For the proper functioning of components and to avoid future bugs and glitches it is necessary that props are passed correctly. Hence, it is required to use props validation to improve the react
    3 min read
  • How to create Date Picker in ReactJS?
    Date pickers provide a simple way to select a single value from a pre-determined set. Material UI for React has this component available for us and it is very easy to integrate. We can create a Date Picker in ReactJS using the following approach: Creating React Application And Installing Module: Ste
    2 min read
  • How to create Calendar in ReactJS ?
    Creating a calendar in React JS can help in React projects like to-do lists, e-commerce sites, Ticket booking sites, and many more apps. It visualizes the day, month, and year data and makes an interacting User interface. PrerequisitesReact JSNode.js & NPMTo create a calendar in React JS we will
    2 min read
  • How to Validate String Date Format in JavaScript ?
    Validating string date format in JavaScript involves verifying if a given string conforms to a specific date format, such as YYYY-MM-DD or MM/DD/YYYY. This ensures the string represents a valid date before further processing or manipulation. There are many ways by which we can validate whether the D
    5 min read
  • How to validate Passport Number is ReactJS?
    Passport Number validation is an important step in order to authenticate the user's passport number. The following example shows how to validate the user's passport number using the npm module in ReactJS.  Syntax:  isPassportNumber(str, countryCode) Parameters: This function accepts two parameters a
    2 min read
  • How to create a form in React?
    React uses forms to allow users to interact with the web page. In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute and that even
    5 min read
  • How to perform form validation in React?
    Form validation in React involves ensuring that the data entered into a form meets certain criteria before submission. In this, we will see the form validation in React. Pre-requisitesNodeJS and NPMReactJSReact useState hookHTML, CSS, and JavaScriptSteps to Create React Application And Installing Mo
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences