-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuseTestForm.ts
More file actions
98 lines (91 loc) · 2.33 KB
/
useTestForm.ts
File metadata and controls
98 lines (91 loc) · 2.33 KB
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 { useState } from 'react'
import { FieldPath, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { TestFormValues } from '@/types'
const defaultValues: TestFormValues = {
name: '',
surname: '',
email: '',
city: '',
phone: '',
points: 0,
postalCode: '',
sex: '',
music: [],
comment: '',
shoeSize: '',
age: '',
education: '',
interests: [],
}
export const useTestForm = () => {
const [error, setError] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const { t } = useTranslation()
const VALIDATION = {
name: { required: t('test_form.errors.name') },
surname: { required: t('test_form.errors.surname') },
email: { required: t('test_form.errors.email') },
phone: {
required: t('test_form.errors.phone'),
pattern: {
value: /[0-9]{3}-[0-9]{3}-[0-9]{3}/,
message: t('test_form.errors.phone_format'),
},
},
postalCode: {
required: t('test_form.errors.postalCode'),
pattern: {
value: /[0-9]{2}-[0-9]{3}/,
message: t('test_form.errors.postalCode_format'),
},
},
city: {
required: t('test_form.errors.city'),
},
shoeSize: { required: t('test_form.errors.shoeSize') },
age: { required: t('test_form.errors.age') },
education: { required: t('test_form.errors.education') },
music: { required: t('test_form.errors.music') },
interests: { required: t('test_form.errors.interests') },
sex: { required: t('test_form.errors.sex') },
}
const {
control,
register,
formState: { errors },
setFocus,
handleSubmit,
} = useForm<TestFormValues>({
mode: 'onTouched',
defaultValues,
})
const onSubmit = async (data: TestFormValues) => {
try {
setIsSubmitting(true)
setError('')
alert('selected points: ' + data.points)
console.log(data)
} catch (e) {
console.log(e)
if (e instanceof Error) {
setError(e.message)
} else {
setError(t('errors.something_went_wrong'))
}
} finally {
setIsSubmitting(false)
}
}
return {
VALIDATION,
submit: handleSubmit(onSubmit),
register,
isSubmitting,
setIsSubmitting,
setFocus: (fieldName: FieldPath<TestFormValues>) => () => setFocus(fieldName),
control,
errors,
error,
}
}