/
formik-yup1.js
68 lines (60 loc) · 1.46 KB
/
formik-yup1.js
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
import React from 'react'
import {
useFormik, Formik, Form, Field,
} from 'formik'
import * as Yup from 'yup'
const initValue = {
name: '',
age: '',
sex: '',
}
const myValidation = Yup.object().shape({
name: Yup.string()
.required('名字 為必填欄位'),
age: Yup.number()
.required('年齡 為必填欄位'),
sex: Yup.string()
.required('性別 為必填欄位'),
})
function FormikYup() {
return (
<Formik
initialValues={initValue}
validationSchema={myValidation}
onSubmit={(values) => {
console.log(values)
}}
>
{({ errors, touched }) => (
<Form>
{/* name */}
<div>
<span>name: </span>
<Field name="name" autocomplete="off" />
{errors.name && touched.name ? (
<div>{errors.name}</div>
) : null}
</div>
{/* age */}
<div>
<span>age: </span>
<Field name="age" autocomplete="off" />
{errors.age && touched.age ? (
<div>{errors.age}</div>
) : null}
</div>
{/* sex */}
<div>
<span>sex: </span>
<Field name="sex" autocomplete="off" />
{errors.sex && touched.sex ? (
<div>{errors.sex}</div>
) : null}
</div>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
)
}
export default FormikYup