Skip to content

Instantly share code, notes, and snippets.

@jonathanpalma
Last active March 7, 2023 16:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanpalma/2c6d5605efffd3cf234e646dd9af483b to your computer and use it in GitHub Desktop.
Save jonathanpalma/2c6d5605efffd3cf234e646dd9af483b to your computer and use it in GitHub Desktop.
Type-safe react hook to use yup validation resolver with react-hook-form
import { useCallback } from 'react';
import { object, ValidationError } from 'yup';
const useYupValidationResolver = (
validationSchema: ReturnType<typeof object>
) =>
useCallback(
async (data) => {
try {
const values = await validationSchema.validate(data, {
abortEarly: false,
});
return {
values,
errors: {},
};
} catch (errors) {
if (errors instanceof ValidationError)
return {
values: {},
errors: errors.inner.reduce(
(allErrors, currentError) => ({
...allErrors,
[currentError.path!]: {
type: currentError.type ?? 'validation',
message: currentError.message,
},
}),
{}
),
};
throw new Error('Error trying to validate form schema');
}
},
[validationSchema]
);
export default useYupValidationResolver;
@dextel2
Copy link

dextel2 commented Nov 28, 2022

How to use it with RHF ?

@slashwhatever
Copy link

@slashwhatever
Copy link

I get a warning on line 25 for Forbidden non-null assertion so can I suggest a minor update:

          return {
            values: {},
            errors: errors.inner.reduce(
              (allErrors, currentError) => ({
                ...allErrors,
                ...(currentError.path && {
                  [currentError.path]: {
                    type: currentError.type ?? "validation",
                    message: currentError.message,
                  },
                }),
              }),
              {}
            ),
          };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment