Last active
March 7, 2023 16:36
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
How to use it with RHF ?
https://react-hook-form.com/advanced-usage/#CustomHookwithResolver
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
How to use it with RHF ?