2019-07-03 20:14:39 +08:00
|
|
|
---
|
|
|
|
order: 23
|
|
|
|
title:
|
|
|
|
zh-CN: 动态校验规则
|
|
|
|
en-US: Dynamic Rules
|
|
|
|
---
|
|
|
|
|
|
|
|
## zh-CN
|
|
|
|
|
|
|
|
根据不同情况执行不同的校验规则。
|
|
|
|
|
|
|
|
## en-US
|
|
|
|
|
|
|
|
Perform different check rules according to different situations.
|
|
|
|
|
|
|
|
```tsx
|
2022-05-21 22:14:15 +08:00
|
|
|
import { Button, Checkbox, Form, Input } from 'antd';
|
|
|
|
import React, { useEffect, useState } from 'react';
|
2019-07-03 20:14:39 +08:00
|
|
|
|
|
|
|
const formItemLayout = {
|
|
|
|
labelCol: { span: 4 },
|
|
|
|
wrapperCol: { span: 8 },
|
|
|
|
};
|
2022-05-19 09:46:26 +08:00
|
|
|
|
2019-07-03 20:14:39 +08:00
|
|
|
const formTailLayout = {
|
|
|
|
labelCol: { span: 4 },
|
|
|
|
wrapperCol: { span: 8, offset: 4 },
|
|
|
|
};
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
const App: React.FC = () => {
|
2019-07-03 20:14:39 +08:00
|
|
|
const [form] = Form.useForm();
|
2020-01-22 12:11:49 +08:00
|
|
|
const [checkNick, setCheckNick] = useState(false);
|
2019-07-03 20:14:39 +08:00
|
|
|
|
2020-01-22 12:11:49 +08:00
|
|
|
useEffect(() => {
|
2019-07-03 20:14:39 +08:00
|
|
|
form.validateFields(['nickname']);
|
2022-05-19 09:46:26 +08:00
|
|
|
}, [checkNick, form]);
|
2019-07-03 20:14:39 +08:00
|
|
|
|
2020-12-17 15:09:18 +08:00
|
|
|
const onCheckboxChange = (e: { target: { checked: boolean } }) => {
|
2019-07-03 20:14:39 +08:00
|
|
|
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>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
export default App;
|
2019-07-03 20:14:39 +08:00
|
|
|
```
|