15

I try to do it like so, but it does nothing...

import {useForm, FormContext} from 'react-hook-form';

const formMethods = useForm({mode: 'onSubmit'});
const {triggerValidation} = formMethods;
triggerValidation('myFieldName');

return (
    <FormContext {...formMethods}>
        //here are my form fields, one of which has the key of 'myFieldName'
    </FormContext>
);
2
  • When do you want to trigger the validation? Commented Dec 1, 2021 at 15:01
  • @TheTisiboth I want to trigger it within the onChange of one input (actually onChange of a wrapper - Controller), to enforce the validation of another input. But regardless, it doesn't work even within the useEffect.. Commented Dec 1, 2021 at 19:19

1 Answer 1

19

you've to use trigger method: https://react-hook-form.com/api/useform/trigger

Sign up to request clarification or add additional context in comments.

4 Comments

hmm this didn't work for me - await trigger() resolves to true and formState.isValid is true before and after calling it, even when one of the fields contains an invalid value
also how can we get latest "errors" object after triggering via trigger(). "errors" contains old object.
@Andy I believe that you need to pass in the full path to the field, i.e. await trigger('fieldName') or if you grouped the form you need to use await trigger('formGroup.fieldName')
The link is no longer valid, here's the new one: react-hook-form.com/docs/useform/trigger

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.