This repository was archived by the owner on May 19, 2025. It is now read-only.
forked from replayio-public/react-hook-form
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisValid.tsx
More file actions
107 lines (99 loc) · 2.61 KB
/
isValid.tsx
File metadata and controls
107 lines (99 loc) · 2.61 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
99
100
101
102
103
104
105
106
107
import * as React from 'react';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { useParams } from 'react-router-dom';
let renderCounter = 0;
const validationSchema = yup
.object()
.shape({
firstName: yup.string().required(),
lastName: yup.string().max(5).required(),
})
.required();
const IsValid: React.FC = () => {
const { mode, defaultValues } = useParams();
const isBuildInValidation = mode === 'build-in';
const [show, setShow] = React.useState(true);
const {
register,
handleSubmit,
unregister,
formState: { isValid },
} = useForm<{
firstName: string;
lastName: string;
hidden: string;
age: string;
location: string;
select: string;
radio: string;
checkbox: string;
}>({
mode: 'onChange',
...(isBuildInValidation ? {} : { resolver: yupResolver(validationSchema) }),
...(defaultValues === 'defaultValues'
? {
defaultValues: {
firstName: 'test',
lastName: 'test1',
},
}
: {}),
});
React.useEffect(() => {
if (isBuildInValidation) {
if (show) {
unregister('hidden');
}
} else {
if (!show) {
unregister('firstName');
}
}
}, [show, isBuildInValidation, unregister]);
renderCounter++;
return (
<form onSubmit={handleSubmit(() => {})}>
{isBuildInValidation ? (
<>
<input {...register('location')} placeholder="location" />
<input
{...register('firstName', { required: true })}
placeholder="firstName"
/>
<input
{...register('lastName', { required: true })}
placeholder="lastName"
/>
{!show && (
<input
{...register('hidden', { required: true })}
placeholder="hidden"
/>
)}
<input {...register('age')} placeholder="age" />
</>
) : (
<>
<input {...register('location')} placeholder="location" />
{show && <input {...register('firstName')} placeholder="firstName" />}
<input {...register('lastName')} placeholder="lastName" />
<input {...register('age')} placeholder="age" />
</>
)}
<div id="isValid">{JSON.stringify(isValid)}</div>
<div id="renderCount">{renderCounter}</div>
<button
type="button"
id="toggle"
onClick={() => {
setShow(!show);
}}
>
Toggle
</button>
</form>
);
};
export const isValid = IsValid;