表单字段有很多异步检查规则,因为复合API可以通过返回不同的结果一次检查这些规则,我不想触发这么多API请求。
语法已更新于
v4
新语法是:
setFields. | Set fields status | (fields: FieldData[]) => void
示例:
form.setFields([
{
name: 'field-to-update',
errors: ['error-string'],
},
]);
使用
form.setFields
语法
Function({ fieldName: { value: any, errors: Error } })
示例来自此处 -
this.props.form.setFields({
user: {
value: values.user,
errors: [new Error('forbid ha')],
},
});
当您需要添加自定义错误消息时,只需使用
validateStatus
&& help
属性。
例如,您的 props 中出现了一个名为 loginError (string) 的错误:
<Form.Item
{ ...props.loginError && {
help: props.loginError,
validateStatus: 'error',
}}>
{getFieldDecorator('email', {
rules: [
{ required: true, message: 'You have to write the email' },
],
})(
<Input size="large"/>,
)}
</Form.Item>
form.setFields([
{
name: "email", // required
value: "myemail@@gmail.com",//optional
errors: ["Invalid email"],
},
]);
我用在
v4.16.11
在 v5 中,您可以使用表单实例上的
setFormFields
方法动态设置错误消息。
<Form
form={form}
onFinish={handleSubmit}
initialValues={{ termsAccepted: false, email: "" }}
className="mt-7"
>
<Form.Item
name="email"
rules={[
{
required: true,
message: ERROR_MESSAGES.required("Email"),
},
{
type: "email",
message: ERROR_MESSAGES.INVALID_EMAIL,
},
]}
>
<Input
label="Email address"
id="email"
type="email"
placeholder="Email address"
size="large"
/>
</Form.Item>
<div className="flex items-center gap-3 mt-4">
<Button type="full" htmlType="submit">
Join Group
</Button>
</div>
</Form>
然后在你的组件代码中。
const [form] = Form.useForm();
form.setFields([
{
name: "email",
errors: ["Please use the email address you were invited with"],
},
]);
请查看文档以获取更多信息。