1

React-datepicker and react-hook-form. I am trying to make react-datepicker required, but its not working

<Controller
    name="resetDateTime"
    control={control}
    required
    render={({ field }) => (
        <Datetime
            onChange={(date) => field.onChange(date)}
            selected={field.value}
            inputProps={{
                placeholder: "MM-DD-YYYY HH:mm",
            }}
            viewMode="time"
        />
    )}
/>
{errors.resetDateTime && <span>This field is required</span>}

When I submit form without selecting any datetime, I am expecting the error to be show, but instead it submits the form

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

0

<Controller /> has no required prop, instead of you have to pass the validation rules via the rules prop. Check the docs for more info.

<Controller
    name="resetDateTime"
    control={control}
    rules={{ required: true }}
    render={({ field }) => (
        <Datetime
            onChange={(date) => field.onChange(date)}
            selected={field.value}
            inputProps={{
                placeholder: "MM-DD-YYYY HH:mm",
            }}
            viewMode="time"
        />
    )}
/>
{errors.resetDateTime && <span>This field is required</span>}
knoefel
  • 5,991
  • 3
  • 29
  • 43