-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathApp.jsx
220 lines (197 loc) · 6.46 KB
/
App.jsx
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// @ts-check
import 'core-js';
import 'regenerator-runtime/runtime';
import 'raf/polyfill';
import { useRef, useState } from 'react';
import { isEqual } from 'lodash-es';
import { createRoot } from 'react-dom/client';
import {
Async,
FieldFeedback,
FieldFeedbacks,
FormWithConstraints,
Input
} from 'react-form-with-constraints-bootstrap';
import { DisplayFields } from 'react-form-with-constraints-tools';
import './index.html';
import './App.scss';
function wait(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function checkUsernameAvailability(value) {
console.info('checkUsernameAvailability');
await wait(1000);
return !['john', 'paul', 'george', 'ringo'].includes(value.toLowerCase());
}
function getInitialInputsState() {
return {
username: '',
password: '',
passwordConfirm: ''
};
}
function Form() {
const form = useRef(null);
const password = useRef(null);
const [inputs, setInputs] = useState(getInitialInputsState());
const [signUpButtonDisabled, setSignUpButtonDisabled] = useState(false);
const [resetButtonDisabled, setResetButtonDisabled] = useState(true);
function shouldDisableResetButton(state) {
return isEqual(getInitialInputsState(), state) && !form.current.hasFeedbacks();
}
async function handleChange({ target }) {
setInputs(prevState => {
return { ...prevState, [target.name]: target.value };
});
await form.current.validateFields(target);
setSignUpButtonDisabled(!form.current.isValid());
setResetButtonDisabled(shouldDisableResetButton(inputs));
}
async function handlePasswordChange({ target }) {
setInputs(prevState => {
return { ...prevState, [target.name]: target.value };
});
await form.current.validateFields(target, 'passwordConfirm');
setSignUpButtonDisabled(!form.current.isValid());
setResetButtonDisabled(shouldDisableResetButton(inputs));
}
async function handleSubmit(e) {
e.preventDefault();
await form.current.validateForm();
const formIsValid = form.current.isValid();
setSignUpButtonDisabled(!form.current.isValid());
setResetButtonDisabled(shouldDisableResetButton(inputs));
if (formIsValid) {
alert(`Valid form\n\ninputs =\n${JSON.stringify(inputs, null, 2)}`);
}
}
function handleReset() {
setInputs(getInitialInputsState());
form.current.resetFields();
setSignUpButtonDisabled(false);
setResetButtonDisabled(true);
}
return (
<FormWithConstraints ref={form} onSubmit={handleSubmit} noValidate>
<div className="mb-3">
<label htmlFor="username">
Username <small>(already taken: john, paul, george, ringo)</small>
</label>
<Input
id="username"
name="username"
value={inputs.username}
onChange={handleChange}
required
minLength={3}
className="form-control is-pending-sm"
/>
<span className="spinner-border spinner-border-sm" />
<FieldFeedbacks for="username">
<FieldFeedback when="tooShort">Too short</FieldFeedback>
<FieldFeedback when="*" />
<Async
promise={checkUsernameAvailability}
pending={<span className="d-block">...</span>}
then={available =>
available ? (
<FieldFeedback key="1" info style={{ color: '#198754' /* $green */ }}>
Username available
</FieldFeedback>
) : (
<FieldFeedback key="2">Username already taken, choose another</FieldFeedback>
)
}
/>
<FieldFeedback when="valid">Looks good!</FieldFeedback>
</FieldFeedbacks>
</div>
<div className="mb-3">
<label htmlFor="password">Password</label>
<Input
type="password"
id="password"
name="password"
innerRef={password}
value={inputs.password}
onChange={handlePasswordChange}
required
pattern=".{5,}"
className="form-control"
/>
<FieldFeedbacks for="password">
<FieldFeedback when="valueMissing" />
<FieldFeedback when="patternMismatch">Should be at least 5 characters long</FieldFeedback>
<FieldFeedback when={value => !/\d/.test(value)} warning>
Should contain numbers
</FieldFeedback>
<FieldFeedback when={value => !/[a-z]/.test(value)} warning>
Should contain small letters
</FieldFeedback>
<FieldFeedback when={value => !/[A-Z]/.test(value)} warning>
Should contain capital letters
</FieldFeedback>
<FieldFeedback when={value => !/\W/.test(value)} warning>
Should contain special characters
</FieldFeedback>
<FieldFeedback when="valid">Looks good!</FieldFeedback>
</FieldFeedbacks>
</div>
<div className="mb-3">
<label htmlFor="password-confirm">Confirm Password</label>
<Input
type="password"
id="password-confirm"
name="passwordConfirm"
value={inputs.passwordConfirm}
onChange={handleChange}
required
className="form-control"
/>
<FieldFeedbacks for="passwordConfirm">
<FieldFeedback when="*" />
<FieldFeedback when={value => value !== password.current.value}>
Not the same password
</FieldFeedback>
<FieldFeedback when="valid">Looks good!</FieldFeedback>
</FieldFeedbacks>
</div>
<button type="submit" disabled={signUpButtonDisabled} className="btn btn-primary">
Sign Up
</button>{' '}
<button
type="button"
onClick={handleReset}
disabled={resetButtonDisabled}
className="btn btn-secondary"
>
Reset
</button>
<pre>
<small>
Fields = <DisplayFields />
</small>
</pre>
</FormWithConstraints>
);
}
function App() {
return (
<div className="container">
<p>
Inspired by{' '}
<a href="https://moduscreate.com/blog/reactjs-form-validation-approaches/">
Modus Create - ReactJS Form Validation Approaches
</a>
<br />
Fixed version:{' '}
<a href="https://codepen.io/tkrotoff/pen/MEeNvO">https://codepen.io/tkrotoff/pen/MEeNvO</a>
</p>
<Form />
</div>
);
}
const root = createRoot(document.getElementById('app'));
root.render(<App />);