ant-design/components/form/demo/dynamic-rule.md

93 lines
2.1 KiB
Markdown
Raw Normal View History

---
order: 13
title:
zh-CN: 动态校验规则
en-US: Dynamic Rules
---
## zh-CN
根据不同情况执行不同的校验规则。
## en-US
Perform different check rules according to different situations.
2019-05-07 14:57:32 +08:00
```jsx
import { Form, Input, Button, Checkbox } from 'antd';
2018-06-27 15:55:04 +08:00
const formItemLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8 },
};
const formTailLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8, offset: 4 },
};
class DynamicRule extends React.Component {
state = {
checkNick: false,
};
2018-06-27 15:55:04 +08:00
check = () => {
2019-05-07 14:57:32 +08:00
this.props.form.validateFields(err => {
if (!err) {
console.info('success');
}
});
};
handleChange = e => {
this.setState(
{
checkNick: e.target.checked,
},
() => {
this.props.form.validateFields(['nickname'], { force: true });
},
);
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
render() {
const { getFieldDecorator } = this.props.form;
return (
<div>
2018-12-22 16:48:30 +08:00
<Form.Item {...formItemLayout} label="Name">
{getFieldDecorator('username', {
2019-05-07 14:57:32 +08:00
rules: [
{
required: true,
message: 'Please input your name',
},
],
})(<Input placeholder="Please input your name" />)}
2018-12-22 16:48:30 +08:00
</Form.Item>
<Form.Item {...formItemLayout} label="Nickname">
{getFieldDecorator('nickname', {
2019-05-07 14:57:32 +08:00
rules: [
{
required: this.state.checkNick,
message: 'Please input your nickname',
},
],
})(<Input placeholder="Please input your nickname" />)}
2018-12-22 16:48:30 +08:00
</Form.Item>
<Form.Item {...formTailLayout}>
2019-05-07 14:57:32 +08:00
<Checkbox checked={this.state.checkNick} onChange={this.handleChange}>
2017-05-15 17:33:47 +08:00
Nickname is required
</Checkbox>
2018-12-22 16:48:30 +08:00
</Form.Item>
<Form.Item {...formTailLayout}>
<Button type="primary" onClick={this.check}>
Check
</Button>
2018-12-22 16:48:30 +08:00
</Form.Item>
</div>
);
}
}
2018-12-17 10:02:08 +08:00
const WrappedDynamicRule = Form.create({ name: 'dynamic_rule' })(DynamicRule);
ReactDOM.render(<WrappedDynamicRule />, mountNode);
2019-05-07 14:57:32 +08:00
```