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 pathsetValueWithTrigger.tsx
More file actions
74 lines (64 loc) · 1.54 KB
/
setValueWithTrigger.tsx
File metadata and controls
74 lines (64 loc) · 1.54 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
import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
let renderCounter = 0;
const SetValueWithTrigger: React.FC = () => {
const {
register,
setValue,
handleSubmit,
formState: { errors },
} = useForm<{
firstName: string;
lastName: string;
}>();
useEffect(() => {
register('firstName', {
required: 'required',
minLength: {
value: 10,
message: 'minLength 10',
},
});
register('lastName', {
validate: (data) => {
if (data === 'bill') {
return true;
}
if (data && data.length < 10) {
return 'too short';
}
return 'error message';
},
});
}, [register]);
renderCounter++;
return (
<form onSubmit={handleSubmit(() => {})}>
<input
name="firstName"
placeholder="firstName"
onChange={(e) =>
setValue('firstName', e.target.value, {
shouldValidate: true,
shouldDirty: true,
})
}
/>
{errors.firstName && <p>{errors.firstName.message}</p>}
<input
name="lastName"
placeholder="lastName"
onChange={(e) =>
setValue('lastName', e.target.value, {
shouldValidate: true,
shouldDirty: true,
})
}
/>
{errors.lastName && <p>{errors.lastName.message}</p>}
<button>Submit</button>
<div id="renderCount">{renderCounter}</div>
</form>
);
};
export const setValueWithTrigger = SetValueWithTrigger;