-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathAsyncValidation.js
More file actions
52 lines (45 loc) · 1.14 KB
/
AsyncValidation.js
File metadata and controls
52 lines (45 loc) · 1.14 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
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import { Debug } from './Debug';
// Async Validation
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const validate = values => {
return sleep(300).then(() => {
const errors = {};
if (['admin', 'null', 'god'].includes(values.username)) {
errors.username = 'Nice try';
}
if (!values.username) {
errors.username = 'Required';
}
if (Object.keys(errors).length) {
throw errors;
}
});
};
const Username = () => (
<div>
<h1>Pick a username</h1>
<Formik
initialValues={{
username: '',
}}
validate={validate}
onSubmit={values => {
sleep(500).then(() => {
alert(JSON.stringify(values, null, 2));
});
}}
render={({ errors, touched }) => (
<Form>
<label htmlFor="username">Username</label>
<Field name="username" type="text" />
<ErrorMessage name="username" />
<button type="submit">Submit</button>
<Debug />
</Form>
)}
/>
</div>
);
export default Username;