forked from react-hook-form/react-hook-form
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomValidation.tsx
83 lines (77 loc) · 2.23 KB
/
customValidation.tsx
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
import React from 'react';
import ReactDOM from 'react-dom';
import { useForm } from 'react-hook-form';
export default function App() {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => {
alert(JSON.stringify(data));
};
const intialValues = {
firstName: 'bill',
lastName: 'luo',
email: '[email protected]',
age: -1,
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="firstName">First Name</label>
<input
defaultValue={intialValues.firstName}
name="firstName"
placeholder="bill"
ref={register({
validate: value => value !== 'bill',
})}
/>
</div>
{errors.firstName && <p>Your name is not bill</p>}
<div>
<label htmlFor="lastName">Last Name</label>
<input
defaultValue={intialValues.lastName}
name="lastName"
placeholder="luo"
ref={register({
validate: value => value.length > 3,
})}
/>
</div>
{errors.lastName && <p>Your last name is less than 3 characters</p>}
<div>
<label htmlFor="email">Email</label>
<input
defaultValue={intialValues.email}
name="email"
placeholder="[email protected]"
type="email"
ref={register}
/>
</div>
<div>
<label htmlFor="age">Age</label>
<input
defaultValue={intialValues.age}
name="age"
placeholder="0"
type="text"
ref={register({
validate: {
positiveNumber: value => parseFloat(value) > 0,
lessThanHundred: value => parseFloat(value) < 200,
},
})}
/>
</div>
{errors.age && errors.age.type === 'positiveNumber' && (
<p>Your age is invalid</p>
)}
{errors.age && errors.age.type === 'lessThanHundred' && (
<p>Your age should be greater than 200</p>
)}
<button type="submit">Submit</button>
</form>
</div>
);
}