Formik + Yup

Example form with useformik + yup

1 import React from 'react';
2 import { useFormik } from 'formik';
3 import * as Yup from 'yup';
4
5 const SignupForm = () => {
6 const formik = useFormik({
7 initialValues: {
8 firstName: '',
9 lastName: '',
10 email: '',
11 },
12 validationSchema: Yup.object({
13 firstName: Yup.string()
14 .max(15, 'Must be 15 characters or less')
15 .required('Required'),
16 lastName: Yup.string()
17 .max(20, 'Must be 20 characters or less')
18 .required('Required'),
19 email: Yup.string().email('Invalid email address').required('Required'),
20 }),
21 onSubmit: values => {
22 alert(JSON.stringify(values, null, 2));
23 },
24 });
25 return (
26 <form onSubmit={formik.handleSubmit}>
27 <label htmlFor="firstName">First Name</label>
28 <input
29 id="firstName"
30 type="text"
31 {...formik.getFieldProps('firstName')}
32 />
33 {formik.touched.firstName && formik.errors.firstName ? (
34 <div>{formik.errors.firstName}</div>
35 ) : null}
36
37 <label htmlFor="lastName">Last Name</label>
38 <input id="lastName" type="text" {...formik.getFieldProps('lastName')} />
39 {formik.touched.lastName && formik.errors.lastName ? (
40 <div>{formik.errors.lastName}</div>
41 ) : null}
42
43 <label htmlFor="email">Email Address</label>
44 <input id="email" type="email" {...formik.getFieldProps('email')} />
45 {formik.touched.email && formik.errors.email ? (
46 <div>{formik.errors.email}</div>
47 ) : null}
48
49 <button type="submit">Submit</button>
50 </form>
51 );
52 };
Formik theo dõi các trường đã truy cập và lưu trữ thông tin trong touched, Key của touched chính là feild name và giá trị của touch là booleans true/false
Thêm handleBlur để touched hoạt động tốt hơn
(To take advantage of touched, we pass formik.handleBlur to each input’s onBlur prop. This function works similarly to formik.handleChange in that it uses the name attribute to figure out which field to update.)
Since Formik authors/users love Yup so much, Formik has a special configuration prop for Yup called validationSchema which will automatically transform Yup’s validation errors messages into a pretty object whose keys match values/initialValues/touched (just like any custom validation function would have to).

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.