Skip to content

Instantly share code, notes, and snippets.

@wardpeet
Last active November 28, 2020 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wardpeet/e6d6af49bb01bd371aa2b574bd5ab9b3 to your computer and use it in GitHub Desktop.
Save wardpeet/e6d6af49bb01bd371aa2b574bd5ab9b3 to your computer and use it in GitHub Desktop.
Formik - async yup
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