1

I want to select a time range with react-datepicker, and also use react-hook-form to validate when onBlur without input, here is my code:

<Controller
    control={control}
    name='time'
    rules={{ required: true }}
    render={({
        field: { value, onChange, onBlur }
    }) => (
        <Datepicker
            dateFormat='yyyy/MM/dd h:mm aa'
            onChange={onChange}
            onBlur={onBlur}
            selected={value}
            showTimeSelect
        />
    )}
/>

I can choose one date and time in one picker and do validation right now, it works, but if I want to choose two date and time in one picker, what should I do? How do I make react-hook-form identify the start or end time in picker? is it possible?

mahooresorkh
  • 1,361
  • 2
  • 8
  • 16
呂學霖
  • 43
  • 2
  • 7

1 Answers1

2

I've got the exact same issue last week, here is the solution...

You just need to pass (at least) the value to the "Controller function", you achieve that using only the field object.

In any case, When the DatePicker component is used for a date range, it will require a two-position vector data type, where the start and end dates are stored as a string. But if you try to manipulate and control this component via the onChange function that comes from the reack-hook-form it's gonna screw up the entire thing, because is made for a one-to-one data flux. Then the processes are done separately but the vector is still sent to the controller. Here is the code!

              const [dateRange, setDateRange] = useState([null, null]);
              const [startDate, endDate] = dateRange;
              <Controller
                //is a prop that we get back from the useForm Hook and pass into the input.
                control={control}
                //is how React Hook Form tracks the value of an input internally.
                name={name}
                //render is the most important prop; we pass a render function here.
                render={({
                  //The function has three keys: field , fieldState, and formState.
                  field, // The field object exports two things (among others): value and onChange
                }) => (
                  <>
                    <DatePicker
                      selectsRange={true}
                      startDate={startDate}
                      endDate={endDate}
                      onChange={(e) => {
                        setDateRange(e);
                        field.onChange(e);
                      }}
                      isClearable={true}
                      className="form-control"
                    />
                  </>
                )}
                rules={{
                  required: `The  ${label} field is required`,
                }}
              />
epimeteo
  • 31
  • 5