I am using react-hook-form library and have a controller for a date picker
According to the documentation, the rules should work exactly as the validation set inside the register.
It works with { required: true }
, but when needing to take into account the value in the field, I can't seem to trigger the error.
For my purpose, I have a function to convert the date from react-datepicker into YYYY-MM-DD, called formatDate
(i.e., formatDate
takes the value from the date picker and returns a string "YYYY-MM-DD"
)
Just for testing purposes, I am trying to trigger the error if the value does not match a certain string in the form YYYY-MM-DD, like this
<Controller
as={<DatePicker />}
name="initialDate"
control={control}
maxDate={dateRef.current}
rules={{ validate: (value) => !value || formatDate(value) === '2020-07-12' }}
/>
The error never triggers
Edit: After some testing, the error does trigger on submitting the form, however, I have set the validation to trigger on blur, and this is the part that does not work. Also note that when I tried the error for { required: true } it triggered on blur without issues
const { handleSubmit, control, watch, setValue, errors, register } = useForm({ mode: 'onBlur'});