Last active
November 28, 2020 08:39
-
-
Save wardpeet/e6d6af49bb01bd371aa2b574bd5ab9b3 to your computer and use it in GitHub Desktop.
Formik - async yup
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 * as React from "react"; | |
import { | |
Formik, | |
Form, | |
Field, | |
validateYupSchema, | |
yupToFormErrors, | |
} from "formik"; | |
const genSignupSchema = (Yup) => | |
Yup.object().shape({ | |
firstName: Yup.string() | |
.min(2, "Too Short!") | |
.max(50, "Too Long!") | |
.required("Required"), | |
lastName: Yup.string() | |
.min(2, "Too Short!") | |
.max(50, "Too Long!") | |
.required("Required"), | |
email: Yup.string().email("Invalid email").required("Required"), | |
}); | |
export const ValidationSchemaExample = () => ( | |
<div> | |
<h1>Signup</h1> | |
<Formik | |
initialValues={{ | |
firstName: "", | |
lastName: "", | |
email: "", | |
}} | |
validate={(values) => { | |
return import("yup") | |
.then((yup) => validateYupSchema(values, genSignupSchema(yup))) | |
.then(() => []) | |
.catch((err) => { | |
// Yup will throw a validation error if validation fails. We catch those and | |
// resolve them into Formik errors. We can sniff if something is a Yup error | |
// by checking error.name. | |
// @see https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string | |
if (err.name === "ValidationError") { | |
return yupToFormErrors(err); | |
} | |
throw err; | |
}); | |
}} | |
onSubmit={(values) => { | |
// same shape as initial values | |
console.log(values); | |
}} | |
> | |
{({ errors, touched }) => ( | |
<Form> | |
<Field name="firstName" /> | |
{errors.firstName && touched.firstName ? ( | |
<div>{errors.firstName}</div> | |
) : null} | |
<Field name="lastName" /> | |
{errors.lastName && touched.lastName ? ( | |
<div>{errors.lastName}</div> | |
) : null} | |
<Field name="email" type="email" /> | |
{errors.email && touched.email ? <div>{errors.email}</div> : null} | |
<button type="submit">Submit</button> | |
</Form> | |
)} | |
</Formik> | |
</div> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment