Created
December 4, 2019 23:39
-
-
Save bryanberger/081d5f59f065cf9cf3d0d22a3648bf96 to your computer and use it in GitHub Desktop.
Formik + Yup
This file contains 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 React from 'react'; | |
import { Formik, Field, Form, ErrorMessage } from 'formik'; | |
import * as Yup from 'yup'; | |
const SignupForm = () => { | |
return ( | |
<Formik | |
initialValues={{ firstName: '', lastName: '', email: '' }} | |
validationSchema={Yup.object({ | |
firstName: Yup.string() | |
.max(15, 'Must be 15 characters or less') | |
.required('Required'), | |
lastName: Yup.string() | |
.max(20, 'Must be 20 characters or less') | |
.required('Required'), | |
email: Yup.string() | |
.email('Invalid email address') | |
.required('Required'), | |
})} | |
onSubmit={(values, { setSubmitting }) => { | |
setTimeout(() => { | |
alert(JSON.stringify(values, null, 2)); | |
setSubmitting(false); | |
}, 400); | |
}} | |
> | |
<Form> | |
<label htmlFor="firstName">First Name</label> | |
<Field name="firstName" type="text" /> | |
<ErrorMessage name="firstName" /> | |
<label htmlFor="lastName">Last Name</label> | |
<Field name="lastName" type="text" /> | |
<ErrorMessage name="lastName" /> | |
<label htmlFor="email">Email Address</label> | |
<Field name="email" type="email" /> | |
<ErrorMessage name="email" /> | |
<button type="submit">Submit</button> | |
</Form> | |
</Formik> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment