user3808307
user3808307

Reputation: 1539

react-hook-form controller with validation based on value

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'});

Upvotes: 4

Views: 3425

Answers (2)

techchintan
techchintan

Reputation: 51

const { handleSubmit, control } = useForm({
  mode: 'onChange',
  reValidateMode: 'onChange'
});

         <Controller
            control={control}
            defaultValue={''}
            render={({ onChange, onBlur }) => (
              <TextFeild
                name="name"
                required
                onChange={onChange}
                onBlur={onBlur}
                errorMessage={'ERORR!'}
              />
            )}
            rules={{
              required: true,
              minLength: 6,
            }}
            name="name"
          ></Controller>

Try to use a controller is like this.

Upvotes: 1

lamhungypl
lamhungypl

Reputation: 195

try useForm({mode:'onBlur'}) From react-hook-form API docs: useForm

Upvotes: 0

Related Questions