Open samkahchiin opened 4 years ago
Have you found a solution ?
For those reading this thread later, a possible workaround is to use a setTimeout around the form.validateFields()
. For some reason, it will validate without the outOfDate error. As a helper method, you can use something like:
const formValidateFields = (form: FormInstance): Promise<any> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
form
.validateFields()
.then((values) => resolve(values))
.catch((e) => reject(e))
})
})
}
I got a same outOfDate = true
problem but cannot be solved by setTimeout
:
I just want to implement a num1
always less than num2
joint form validation .
import React from 'react';
import './index.css';
import { Button, Form, InputNumber } from 'antd';
const alert = (msg, data) => {
window.alert(msg + ': ' + JSON.stringify(data, null, 2));
}
const App = () => {
const [form] = Form.useForm();
const onFinish = async() => {
try {
await form.validateFields()
} catch (err) {
alert('validateFields error', err)
return;
}
const values = form.getFieldsValue()
alert('form values', values)
};
return (
<Form
form={form}
labelCol={{
span: 8,
}}
wrapperCol={{
span: 16,
}}
>
<Form.Item
label="num1"
name="num1"
rules={[
({ validateFields }) => ({
validator() {
return new Promise((resolve, reject) => {
validateFields(['num2']).then(
(value) => {
console.log(value);
return resolve();
},
(reason) => {
console.log(reason);
return resolve();
}
);
});
},
}),
]}
>
<InputNumber />
</Form.Item>
<Form.Item
label="num2"
name="num2"
rules={[
{
validator: (_, value) => {
if (value > form.getFieldValue('num1')) {
return Promise.reject("num2 can't more than num1");
} else {
return Promise.resolve();
}
},
},
]}
>
<InputNumber />
</Form.Item>
<Button type="primary" htmlType="submit" onClick={onFinish}>
OK
</Button>
</Form>
);
};
export default App;
I fixed my problem with setTimeout
and callback
. the point here is move the validation to next turn instead of waiting for the promise. So the "setTimeout-with-promise" walkaround not work for me. My "setTimout-with-callback" solution:
rules={[
{
validator: (rule, value, callback) => {
setTimeout(() => {
form.validateFields(['num2']);
});
callback();
},
},
]}
The code works perfectly fine in the apps. However, when I tested it using Jest, it will always return error upon calling
form.validateFields()
. The sample error returned isI try to look at the source code and it said outOfDate means
change when validating
.Does anybody knows how to avoid this error?
Here is my sample test codes
In apps