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}
/>

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.

const initialDate = new Date();

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

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.

30