DEV Community

Cover image for How to validate with react-datepicker
off.tokyo
off.tokyo

Posted on

How to validate with react-datepicker

Using react-datepicker, you can easily create a datepicker.

In this article, I'll show you how to validate with react-datepicker.

Specifically, let's consider a situation where you need to enter your date of birth, for example, when registering user information for a web service.

The idea is to use a validation to tell the user that they must be at least 15 years old to register.

How to validate with react-datepicker

First, suppose we have a DatePicker component like the one below, and we use the argument maxDate.

If you have a DatePicker component like the one below, you can use the argument "maxDate" to make it impossible to set a date before ●●●●.

<DatePicker
selected={startDate}
onChange={handleChange}
maxDate={TimeValidation}
/>
Enter fullscreen mode Exit fullscreen mode

Now, let's look at TimeValidation and see what happens.

By specifying 15 years ago (5475 days ago) from today's date, you can only select dates from earlier dates.

For example, if the year is 2021, only people born before 2006 will be able to enter their date of birth.

TimeValidation

const initialDate = new Date();

const TimeValidation = initialDate.setDate(initialDate.getDate() - 5475);

Enter fullscreen mode Exit fullscreen mode

That's it.

There are many other arguments that can be used in react-datepicker, so please look into them.

I refer to the following article.

React Datepicker and Timepicker Component with Validation using react-datepicker Example Application datepicker-using-react-datepicker/)

How to validate with react-datepicker off.tokyo

Top comments (0)