Search code examples
reactjsmaterial-uireact-hook-formyup

how to use react hook form validation onchange of the textfield in react


form that i want to validate

i am seeing to validate these form in react hoook forms with mui component text field . the problem is its validating the form on submit, but i need to validate it on change of the text field

const eventSchema = yup.object().shape({
  title: yup
    .string()
    .max(128, requiredLimit)
    .required(requiredField)
    .nullable(),
});
const useFunction = useForm({
    defaultValues: defaultValue,
    resolver: yupResolver(eventSchema),
  });
  const { handleSubmit, reset, control, register, formState } = useFunction;
  const { errors } = formState;

  useEffect(() => {
    reset(defaultValue);
  }, [
    defaultValue.title,
  ]);
   <FormInputText
              name='title'
              type='text'
              control={control}
              label='Title'
              helperText={errors?.title?.message}
              errors={!!errors.title}
              register={register('title', {
                onChange: (e) => dispatch(setTitle(e.target.value)),
              })}
            />

Solution

  • you can add mode prop

    https://react-hook-form.com/api/useform/

    mode: onChange | onBlur | onSubmit | onTouched | all = 'onSubmit'

    const useFunction = useForm({
        mode: 'onBlur', // new prop added
        defaultValues: defaultValue,
        resolver: yupResolver(eventSchema),
      });