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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
import useInput from "../hooks/use-input";
// 驗證邏輯
const isNotEmpty = (value) => value.trim() !== "";
const isEmail = (value) => value.includes("@");
const BasicForm = (props) => {
// 套用custom hook,取新變數名區隔狀態
const {
value: firstNameValue,
isValid: firstNameIsValid,
hasError: firstNameHasError,
valueChangeHandler: firstNameChangeHandler,
inputBlurHandler: firstNameBlurHandler,
reset: resetFirstName,
//驗證邏輯
} = useInput(isNotEmpty);
const {
value: lastNameValue,
isValid: lastNameIsValid,
hasError: lastNameHasError,
valueChangeHandler: lastNameChangeHandler,
inputBlurHandler: lastNameBlurHandler,
reset: resetLastName,
//驗證邏輯
} = useInput(isNotEmpty);
const {
value: emailValue,
isValid: emailIsValid,
hasError: emailHasError,
valueChangeHandler: emailChangeHandler,
inputBlurHandler: emailBlurHandler,
reset: resetEmail,
//驗證邏輯
} = useInput(isEmail);
let formIsValid = false;
// 都過了才可以提交
if (firstNameIsValid && lastNameIsValid && emailIsValid) {
formIsValid = true;
}
const submitHandler = (event) => {
event.preventDefault();
if (!formIsValid) {
return;
}
console.log("Submitted!");
console.log(firstNameValue, lastNameValue, emailValue);
//提交後還原狀態
resetFirstName();
resetLastName();
resetEmail();
};
// 動態驗證error樣式
const firstNameClasses = firstNameHasError
? "form-control invalid"
: "form-control";
const lastNameClasses = lastNameHasError
? "form-control invalid"
: "form-control";
const emailClasses = emailHasError ? "form-control invalid" : "form-control";
return (
<form onSubmit={submitHandler}>
<div className='control-group'>
<div className={firstNameClasses}>
<label htmlFor='name'>First Name</label>
// value綁定狀態 onChange變更值 onBlur觸發驗證
<input
type='text'
id='name'
value={firstNameValue}
onChange={firstNameChangeHandler}
onBlur={firstNameBlurHandler}
/>
{firstNameHasError && (
<p className='error-text'>Please enter a first name.</p>
)}
</div>
<div className={lastNameClasses}>
<label htmlFor='name'>Last Name</label>
<input
type='text'
id='name'
value={lastNameValue}
onChange={lastNameChangeHandler}
onBlur={lastNameBlurHandler}
/>
{lastNameHasError && (
<p className='error-text'>Please enter a last name.</p>
)}
</div>
</div>
<div className={emailClasses}>
<label htmlFor='name'>E-Mail Address</label>
<input
type='text'
id='name'
value={emailValue}
onChange={emailChangeHandler}
onBlur={emailBlurHandler}
/>
{emailHasError && (
<p className='error-text'>Please enter a valid email address.</p>
)}
</div>
<div className='form-actions'>
<button disabled={!formIsValid}>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
|