9

I am using React date-picker for my form. Currently it's working well, but the user can delete the date and enter whatever values. How do I restrict it?

This is my code:

import DatePicker from "react-datepicker";

    <DatePicker
    name="invoiceDate"
    className="form-control form-control-sm"
    type="text"
    size="sm"
    placeholder=""
    selected={date}
    minDate={new Date()}
    value={values.setDate}
    onChange={datePickerChange}
    dateFormat="dd/MM/yyyy"
    />
Costa
  • 1,794
  • 1
  • 12
  • 21
Kumara
  • 471
  • 2
  • 10
  • 33

3 Answers3

18

Just add this line of code to DatePicker :

onKeyDown={(e) => {
    e.preventDefault();
}}

After adding this event, your component's code will be like the below code :

<DatePicker
    name="invoiceDate"
    className="form-control form-control-sm"
    type="text"
    size="sm"
    placeholder=""
    selected={date}
    minDate={new Date()}
    value={values.setDate}
    onChange={datePickerChange}
    dateFormat="dd/MM/yyyy"
    onKeyDown={(e) => {
       e.preventDefault();
    }}
  />

Edit patient-silence-ybz45

Majid M.
  • 4,467
  • 1
  • 11
  • 29
1

I think onBeforeInput should be used in this case, as opposed to onKeyDown.

So just simply:

onBeforeInput={(e) => {
    e.preventDefault();
}}

The reason being, that onKeyDown prevents a lot of 'normal' functionality from working when the input is focused. E.g.:

  • Page reload with CTRL + R
  • Opening devtools with F12
  • Going to the next input with Tab

And in case of ReactDatePicker, the customInput property has to be used to pass in an input that has onBeforeInput overridden as explained.

andras
  • 3,305
  • 5
  • 30
  • 45
1

Just add this line of code to DatePicker:

disabledKeyboardNavigation={false}
format="dd/MM/yy"

You can add your date format; It will only take date.