JavaScript-en React-en

How to validate with react-datepicker

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

 

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

 

In this article, I'll show you how to use react-datepicker to validate the date of birth of a user.

 

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

 

How to do validation 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, and you use the argument maxDate, you can make it so that you can't set the date before ●●●●.

 

<DatePicker
selected={startDate}
onChange={handleChange}
maxDate={TimeValidation}
/>

 

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

 

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

 

For example, if the year is 2021, only people born before 2006 can enter their birth date.

 

const initialDate = new Date();

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

 

 

 

 

 

That's all.

 

There are many other arguments that can be used for react-datepicker, so please check out the different ones.

 

I found the following article helpful.

 

 

 

Translated with www.DeepL.com/Translator (free version)

Pocket
LinkedIn にシェア

  • この記事を書いた人

藤沢瞭介(Ryosuke Hujisawa)

りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

-JavaScript-en, React-en

Copyright© off.tokyo , 2021 All Rights Reserved Powered by AFFINGER5.