ant design中form组件validatetrigger怎么用
时间: 2023-11-27 17:05:33 浏览: 733
在 Ant Design 中,`Form` 组件提供了多种验证方式,可以通过设置 `validateTrigger` 属性来指定触发验证的时机。默认情况下,`validateTrigger` 属性的值为 `'onChange'`,即在表单项的值发生变化时进行验证。除此之外,还有 `'onBlur'`、`'onSubmit'` 等多种验证时机可供选择。
以下是一个示例:
```jsx
import { Form, Input, Button } from 'antd';
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16,
},
};
const Demo = () => {
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
return (
<Form
{...layout}
name="basic"
initialValues={{
remember: true,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="用户名"
name="username"
rules={[
{
required: true,
message: '请输入用户名',
},
]}
validateTrigger={['onChange', 'onBlur']}
>
<Input />
</Form.Item>
<Form.Item
label="密码"
name="password"
rules={[
{
required: true,
message: '请输入密码',
},
]}
validateTrigger={['onChange', 'onBlur']}
>
<Input.Password />
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
提交
</Button>
</Form.Item>
</Form>
);
};
export default Demo;
```
在上面的示例中,通过设置 `validateTrigger` 属性为 `['onChange', 'onBlur']`,在输入框的值发生变化或者失去焦点时进行验证。如果验证不通过,则会显示相应的错误提示信息。如果验证通过,则可以提交表单。需要注意的是,在提交表单前,还需要在 `Form` 组件中设置 `onFinish` 和 `onFinishFailed` 属性来处理表单提交成功和失败的情况。
阅读全文
相关推荐













