validateForm accept a different validateSchema #2753
Unanswered
matheusleandroo
asked this question in
General
Replies: 1 comment
-
|
import { useFormikContext } from 'formik';
import { validateYupSchema, yupToFormErrors } from 'formik';
import * as Yup from 'yup';
function MyComponent() {
const { values, setErrors } = useFormikContext();
async function validateWithAlternateSchema() {
const alternateSchema = Yup.object({
email: Yup.string().email().required(),
// ... different rules
});
try {
await validateYupSchema(values, alternateSchema, true);
setErrors({}); // no errors
return true;
} catch (err) {
const errors = yupToFormErrors(err);
setErrors(errors);
return false;
}
}
return (
<button type="button" onClick={validateWithAlternateSchema}>
Validate with alternate schema
</button>
);
}
If you use Zod instead of Yup: import { toFormikValidationSchema } from 'zod-formik-adapter';
const alternateSchema = z.object({ ... });
const errors = await alternateSchema.safeParseAsync(values);
if (!errors.success) {
const formikErrors = {};
errors.error.issues.forEach(i => {
set(formikErrors, i.path.join('.'), i.message);
});
setErrors(formikErrors);
}Feature request note: this pattern is intentional — if you find yourself needing different schemas for different actions, consider splitting into multiple |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi!
I think it would be a good idea if the validateForm function could receive a different validationSchema as a parameter (otherwise it takes the default).
Beta Was this translation helpful? Give feedback.
All reactions