Answers for "formik validation schema"

0

formik validation schema

import React from 'react';
2 import { Formik, Form, Field } from 'formik';
3 import * as Yup from 'yup';
4 
5 const SignupSchema = Yup.object().shape({
6   firstName: Yup.string()
7     .min(2, 'Too Short!')
8     .max(50, 'Too Long!')
9     .required('Required'),
10   lastName: Yup.string()
11     .min(2, 'Too Short!')
12     .max(50, 'Too Long!')
13     .required('Required'),
14   email: Yup.string().email('Invalid email').required('Required'),
15 });
16 
17 export const ValidationSchemaExample = () => (
18   <div>
19     <h1>Signup</h1>
20     <Formik
21       initialValues={{
22         firstName: '',
23         lastName: '',
24         email: '',
25       }}
26       validationSchema={SignupSchema}
27       onSubmit={values => {
28         // same shape as initial values
29         console.log(values);
30       }}
31     >
32       {({ errors, touched }) => (
33         <Form>
34           <Field name="firstName" />
35           {errors.firstName && touched.firstName ? (
36             <div>{errors.firstName}</div>
37           ) : null}
38           <Field name="lastName" />
39           {errors.lastName && touched.lastName ? (
40             <div>{errors.lastName}</div>
41           ) : null}
42           <Field name="email" type="email" />
43           {errors.email && touched.email ? <div>{errors.email}</div> : null}
44           <button type="submit">Submit</button>
45         </Form>
46       )}
47     </Formik>
48   </div>
49 );
Posted by: Guest on March-17-2022

Browse Popular Code Answers by Language