Search code examples
reactjsreact-nativeformikreact-hook-form

How to validate one field at once in react hook form with yup


I have a quiz component that renders different components but i am using single form for them, i want the validation to happen one data a time from:

export const QUIZ_SCHEMA = yup.object().shape({
  radioGroup: yup.number().required('Please select an option to proceed'),
  arrangedText: yup.array().length(5, 'Please answer the question to proceed'),
  essay: yup
    .string()
    .required('Answer is required')
    .min(2, 'Min 2 characters required')
    .max(1000, 'Max 1000 characters allowed'),
});

That is when radio button component is rendered it should validate for that only and so on.

  const {
    control,
    handleSubmit,
    formState: { errors, isValid },
    reset,
  } = useForm({
    defaultValues: {
      radioGroup: undefined,
      arrangedText: [],
      essay: '',
    },
    resolver: yupResolver(QUIZ_SCHEMA),
  });

Solution

  • Formik does provide the following props

    • validateForm
    • validateField
    • validateOnBlur
    • validateOnChange
    • validateOnMount

    You can use these to customize the way you want validation to work.
    I have attached the link to formik documentation below.
    Hope this helps!
    Click here to see official Formik Documentation