mirror of
https://github.com/ant-design/ant-design.git
synced 2024-12-05 09:49:57 +08:00
55e0d13234
* chore: Add demo tsx check * chore: Prettier * chore: Fix lint * fix: Upload ts definition * chore: Demo onlt * docs: Fix demo * chore: Add CI action * chore: Use real name * chore: fix ts define * chore: fix more ts * chore: fix more ts * chore: More ts * chore: More ts * chore: More ts * chore: More ts * chore: More ts * chore: More ts * chore: More ts * chore: Update all rest TS demo * fix test case
94 lines
2.0 KiB
Markdown
94 lines
2.0 KiB
Markdown
---
|
|
order: 23
|
|
title:
|
|
zh-CN: 动态校验规则
|
|
en-US: Dynamic Rules
|
|
---
|
|
|
|
## zh-CN
|
|
|
|
根据不同情况执行不同的校验规则。
|
|
|
|
## en-US
|
|
|
|
Perform different check rules according to different situations.
|
|
|
|
```tsx
|
|
import React, { useState, useEffect } from 'react';
|
|
import { Form, Input, Button, Checkbox } from 'antd';
|
|
|
|
const formItemLayout = {
|
|
labelCol: { span: 4 },
|
|
wrapperCol: { span: 8 },
|
|
};
|
|
const formTailLayout = {
|
|
labelCol: { span: 4 },
|
|
wrapperCol: { span: 8, offset: 4 },
|
|
};
|
|
|
|
const DynamicRule = () => {
|
|
const [form] = Form.useForm();
|
|
const [checkNick, setCheckNick] = useState(false);
|
|
|
|
useEffect(() => {
|
|
form.validateFields(['nickname']);
|
|
}, [checkNick]);
|
|
|
|
const onCheckboxChange = (e: { target: { checked: boolean } }) => {
|
|
setCheckNick(e.target.checked);
|
|
};
|
|
|
|
const onCheck = async () => {
|
|
try {
|
|
const values = await form.validateFields();
|
|
console.log('Success:', values);
|
|
} catch (errorInfo) {
|
|
console.log('Failed:', errorInfo);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Form form={form} name="dynamic_rule">
|
|
<Form.Item
|
|
{...formItemLayout}
|
|
name="username"
|
|
label="Name"
|
|
rules={[
|
|
{
|
|
required: true,
|
|
message: 'Please input your name',
|
|
},
|
|
]}
|
|
>
|
|
<Input placeholder="Please input your name" />
|
|
</Form.Item>
|
|
<Form.Item
|
|
{...formItemLayout}
|
|
name="nickname"
|
|
label="Nickname"
|
|
rules={[
|
|
{
|
|
required: checkNick,
|
|
message: 'Please input your nickname',
|
|
},
|
|
]}
|
|
>
|
|
<Input placeholder="Please input your nickname" />
|
|
</Form.Item>
|
|
<Form.Item {...formTailLayout}>
|
|
<Checkbox checked={checkNick} onChange={onCheckboxChange}>
|
|
Nickname is required
|
|
</Checkbox>
|
|
</Form.Item>
|
|
<Form.Item {...formTailLayout}>
|
|
<Button type="primary" onClick={onCheck}>
|
|
Check
|
|
</Button>
|
|
</Form.Item>
|
|
</Form>
|
|
);
|
|
};
|
|
|
|
ReactDOM.render(<DynamicRule />, mountNode);
|
|
```
|