2018-03-30 17:36:17 -04:00
|
|
|
import React from 'react';
|
2018-09-14 12:45:55 -04:00
|
|
|
import { Formik, Field, Form, ErrorMessage } from 'formik';
|
|
|
|
|
import { Debug } from './Debug';
|
2018-03-30 17:36:17 -04:00
|
|
|
|
|
|
|
|
// Async Validation
|
2020-09-24 14:49:47 -04:00
|
|
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
2018-03-30 17:36:17 -04:00
|
|
|
|
2020-09-24 14:49:47 -04:00
|
|
|
const validate = values => {
|
2018-03-30 17:36:17 -04:00
|
|
|
return sleep(300).then(() => {
|
2019-11-01 20:27:10 +01:00
|
|
|
const errors = {};
|
2018-03-30 17:36:17 -04:00
|
|
|
|
|
|
|
|
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}
|
2020-09-24 14:49:47 -04:00
|
|
|
onSubmit={values => {
|
2018-03-30 17:36:17 -04:00
|
|
|
sleep(500).then(() => {
|
|
|
|
|
alert(JSON.stringify(values, null, 2));
|
|
|
|
|
});
|
|
|
|
|
}}
|
|
|
|
|
render={({ errors, touched }) => (
|
|
|
|
|
<Form>
|
|
|
|
|
<label htmlFor="username">Username</label>
|
|
|
|
|
<Field name="username" type="text" />
|
2018-09-14 12:45:55 -04:00
|
|
|
<ErrorMessage name="username" />
|
2018-03-30 17:36:17 -04:00
|
|
|
<button type="submit">Submit</button>
|
2018-09-14 12:45:55 -04:00
|
|
|
<Debug />
|
2018-03-30 17:36:17 -04:00
|
|
|
</Form>
|
|
|
|
|
)}
|
|
|
|
|
/>
|
|
|
|
|
</div>
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
export default Username;
|