I'm trying to programmatically submit and ant design (v4.3.4) form with validation but form.validateFields() always fails with outOfDate: true if it is inside onValuesChange(). (This form is a part of a larger form factory so I will eventually have to pass the form component to a props function which will then call submit.
const FormA = (props: StepProps) => {
const [form] = useForm();
return (
<Form
form={form}
name="form-a"
onValuesChange={async (changedValues, allValues) => {
form.validateFields().
then(values => console.log("PASSED").
catch(errorInfo => console.log("FAILED", errorInfo));
}}
>
<Form.Item
rules={[{ required: true }]}
name="item-a">
<Input />
</Form.Item>
<Form.Item
rules={[{ required: true }]}
name="item-b"
>
<Input />
</Form.Item>
<Form.Item
rules={[{ required: true }]}
name="item-c"
>
<Input />
</Form.Item>
</Form>
);
};
export default FormA;
I have called the form.validatedField() function onValuesChange. I never get "PASSED" in the console, even when all inputs have values I always get 'FAILED' with the following errorInfo:
{
errorFields: []
outOfDate: true
values: { ..}
}
If I remove the form.validateFields() from onValuesChange then it works fine.
I can't seem to figure out what is outOfDate and why does validation always fail in onValuesChange function.
The best way to programmatically submit a form is by using form.submit() that's part of the form instance. This function will submit and validate your form. Based on the validation result, onFinish or onFinishFailed will be called (see Form API).
const FormA = (props: StepProps) => {
const [form] = useForm();
const handleOnFinish = (values) => {
// handle valid form submission
}
const handleOnFinishFailed = ({ values, errorFields, outOfDate }) => {
// handle invalid form submission
}
return (
<Form
form={form}
name="form-a"
onFinish={handleOnFinish]
onFinishFailed={handleOnFinishFailed}
>
...
</Form>
);
};
export default FormA;
The outOfDate issue is resolved when using this method. If you need additional validation handling for a form item, you can use onChange and form.validateFields() in the components (see issue).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With