Formik with Yup

Form with Formik with Yup

How to

TBC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import React from 'react';
import { Formik } from 'formik';
import * as Yup from 'yup';

const loginFormSchema = Yup.object({
email: Yup.string().email('Email is not valid').required('Email is required'),
password: Yup.string()
.required('Password is required')
.min(8, 'Password must be at least 8 chars'),
});

const initialLoginFormValues = {
email: '',
password: '',
};

const LoginForm = () => {
const handleLoginFormSubmit = (values, { setSubmitting, resetForm }) => {
setTimeout(() => {
console.log(values);
resetForm();
setSubmitting(false);
}, 500);
};
return (
<div className='App'>
<h3>Login Form with Formik and Yup</h3>

<Formik
initialValues={initialLoginFormValues}
onSubmit={handleLoginFormSubmit}
validationSchema={loginFormSchema}
>
{(props) => {
const {
dirty,
errors,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
isValid,
touched,
values,
} = props;
return (
<form autoComplete='off' onSubmit={handleSubmit}>
<div>
<label htmlFor='email'>Email: </label>
<input
className={touched.email && errors.email ? 'has-error' : null}
id='email'
name='email'
onBlur={handleBlur}
onChange={handleChange}
type='text'
value={values.email}
/>
{touched.email && errors.email ? (
<div className='error-message'>{errors.email}</div>
) : null}
</div>
<div>
<label htmlFor='password'>Password: </label>
<input
className={
touched.password && errors.password ? 'has-error' : null
}
id='password'
name='password'
onBlur={handleBlur}
onChange={handleChange}
type='password'
value={values.password}
/>
{touched.password && errors.password ? (
<div className='error-message'>{errors.password}</div>
) : null}
</div>

<button
type='submit'
disabled={!(isValid && dirty) || isSubmitting}
>
{isSubmitting ? 'Logging in...' : 'Login'}
</button>

<pre>{JSON.stringify(values, null, 2)}</pre>
<pre>{JSON.stringify(errors, null, 2)}</pre>
</form>
);
}}
</Formik>
</div>
);
};

export default LoginForm;

Refs