Skip to content
This repository has been archived by the owner on Oct 6, 2020. It is now read-only.

fix(validations): Fix handling of async validations as well as order of onChange notification #57

Merged
merged 3 commits into from
Aug 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions src/Form/Formbot.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,22 @@ export default class Formbot extends React.Component {
const fieldValue = this.state.values[field];
let errorMsg;

try {
if (hasSchema && typeof validation.validate === 'function') {
validation.validate(fieldValue, validationOpts).catch(e => {
this.setErrors({ [field]: e.message }, resolve);
});
if (hasSchema && typeof validation.validate === 'function') {
validation.validate(fieldValue, validationOpts)
.catch(e => {
errorMsg = e.message;
})
.finally(() => {
this.updateField(field, { validated: true }).then(() => {
this.setErrors({ [field]: errorMsg }, resolve);
});
})

return;
} else if (typeof validation === 'function') {
return;
}

try {
if (typeof validation === 'function') {
validation(fieldValue);
} else {
Object.keys(validation).forEach(method => {
Expand Down Expand Up @@ -200,10 +208,9 @@ export default class Formbot extends React.Component {
},
},
() => {
this.props.onChange(field, value, this.state.values);
this.updateField(field, { validated: false }).then(() => {
this.validateField(field);
});
this.updateField(field, { validated: false })
.then(() => this.validateField(field))
.then(() => this.props.onChange(field, value, this.state.values))
}
);
};
Expand Down
51 changes: 22 additions & 29 deletions src/Form/Formbot.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -47,36 +47,29 @@ Quickly build a form using a Formbot and pre-configured form components. Formbot

### Async Validation

```jsx
<Formbot
validationSchema={{
state: yup.string().required(),
zip: yup
.string()
.min(5)
.required()
.test('valid', 'Zip does not match selected state!', async function(value) {
const {
options: {
context: { values }, // Formbot context
},
} = this;

const stateFromZip = await getStateFromZip(value);

return stateFromZip === values.state;
<Playground>
<Formbot
validationSchema={{
random: yup.string().test('valid', 'This test was delayed by 2 seconds.', async function(value) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(false);
}, 2000);
});
}),
}}>
<Form>
<Input name="state" label="State" />
<Input name="zip" label="Zip" />

<Field>
<Button type="submit">Update</Button>
</Field>
</Form>
</Formbot>
```
}}>
<Form>
<Input name="random" label="random" />

<Field>
<Button type="submit">
Sign In
</Button>
</Field>
</Form>

</Formbot>
</Playground>

### Entire Form

Expand Down