Elena Mazyrina
Elena Mazyrina

Reputation: 31

Using array of error messages per one validation rule in react hook form

Use react-hook-form version 7.11.1.

I have a simple control which is expected to show multiple error messages per one validation rule when it is invalid. When I register this control I provide an "validate" option with a custom validation function. From validate option contract I see that my custom validation function should return ValidateResult type. This type can be: Message | Message[] | boolean | undefined (where Message is string). So I assume that I can return array of error messages if control is invalid. But if I return not a string but array, I can't access my error messages anywhere: formState.errors.filedName.mesage is empty.

Is there any way to use array of error messages to show them all in the interface?

My simple component is below:

export const ControlWithErrorsExample = () => {
    const {
        register,
        formState: { errors },
    } = useForm({
        mode: 'onChange',
    });

    const { testValue: testValueError } = errors;

    const validateField = (v: string): ValidateResult => {
        if (v.length > 3) {
            return ['Incorrect value', 'Max length should be equal or less than 3'];
        }

        return undefined;
    };

    useEffect(() => {
        console.log(`I need to get access to my error messages array but got: ${testValueError?.message}`);
    }, [testValueError]);

    return <input type="text" {...register('testValue', { validate: (v) => validateField(v) })} />;
};

Upvotes: 3

Views: 5574

Answers (1)

Joris
Joris

Reputation: 2796

You can't achieve your needs with the validate function.

Why Message[]?
This typing is used by resolvers, resolver is the only way to achieve your needs. You can build your own or use ours: https://github.com/react-hook-form/resolvers

Here is a sample of an array of messages:

"birthYear": Object {
  "message": "Expected number, received string",
  "ref": undefined,
  "type": "invalid_type",
  "types": Object {
    "invalid_type": Array [
      "Expected number, received string",
      "Expected undefined, received string",
    ],
    "invalid_union": "Invalid input",
  },
},

👉🏻 Sample from the Zod snapshot

One more thing, to have all errors, you should use criteriaMode: 'all' with useForm

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

Feel free to open a RFC: https://github.com/react-hook-form/react-hook-form/discussions

Upvotes: 2

Related Questions