Last active
March 1, 2022 12:59
-
-
Save markoarthofer22/8c39ff20c1e30a78a4034221d4f8dd35 to your computer and use it in GitHub Desktop.
Formik with Yup validation
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
.App { | |
text-align: center; | |
} | |
.App form { | |
display: flex; | |
flex-direction: column; | |
max-width: 300px; | |
width: 100%; | |
margin: 0 auto; | |
} | |
.App form label { | |
margin-bottom: 5px; | |
} | |
.App form input { | |
padding: 10px 5px; | |
border: 1px solid black; | |
border-radius: 4px; | |
} | |
.App form button { | |
padding: 10px 15px; | |
border: 1px solid black; | |
border-radius: 4px; | |
background-color: transparent; | |
color: black; | |
transition: all 0.4s ease; | |
max-width: 160px; | |
cursor: pointer; | |
margin: 0 auto; | |
} | |
.App form button:hover { | |
background-color: black; | |
color: white; | |
} | |
.error { | |
color: red; | |
font-weight: 600; | |
font-size: 12px; | |
text-align: left; | |
margin-bottom: 15px; | |
padding: 2px 5px; | |
} |
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 * as React from 'react'; | |
import * as Yup from 'yup'; | |
import './App.css'; | |
import { Formik, Field, Form } from 'formik'; | |
const SignupSchema = 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('Field is required'), | |
}); | |
function App() { | |
return ( | |
<div className='App'> | |
<h1>Signup</h1> | |
<Formik | |
initialValues={{ | |
firstName: '', | |
lastName: '', | |
email: '', | |
}} | |
validationSchema={SignupSchema} | |
onSubmit={(values) => { | |
// same shape as initial values | |
console.log(values); | |
}} | |
> | |
{({ errors, touched }) => ( | |
<Form> | |
<Field name='firstName' /> | |
{errors.firstName && touched.firstName ? ( | |
<div className='error'>{errors.firstName}</div> | |
) : null} | |
<Field name='lastName' /> | |
{errors.lastName && touched.lastName ? ( | |
<div className='error'>{errors.lastName}</div> | |
) : null} | |
<Field name='email' type='email' /> | |
{errors.email && touched.email ? ( | |
<div className='error'>{errors.email}</div> | |
) : null} | |
<button type='submit'>Submit</button> | |
</Form> | |
)} | |
</Formik> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment