本文以antd3.x版本为例,函数组件
表单html:
<Form onSubmit={handleSubmit}>
<Row style={{ margin: 20 }}>
<Col span={12}>
<Form.Item {...formItemLayout} label="身份证号">
{getFieldDecorator("idCard", {
rules: [
{
required: !getFieldValue("accountCard"),
validator: validate,
},
],
})(
<Input
placeholder="请输入身份证号"
allowClear
onChange={handleValide}
/>
)}
</Form.Item>
</Col>
<Col span={12}>
<Form.Item {...formItemLayout} label="账卡号">
{getFieldDecorator("accountCard", {
rules: [
{ required: !getFieldValue("idCard"), validator: validate },
],
})(
<Input
placeholder="请输入账卡号"
allowClear
onChange={handleValide}
/>
)}
</Form.Item>
</Col>
</Row>
<Row>
<Form.Item wrapperCol={{ span: 12, offset: 5 }}>
<Button type="primary" htmlType="submit">
提交
</Button>
<Button onClick={handleReset} style={{ marginLeft: 20 }}>
重置
</Button>
</Form.Item>
</Row>
</Form>
js:
const { getFieldDecorator, setFields, validateFields, getFieldValue } = props.form;
const handleReset = () => {
props.form.resetFields();
};
const handleSubmit = (e) => {
e.preventDefault();
validateFields((err, values) => {
if (!err) {
console.log("Received values of form: ", values);
}
});
};
// 自定义校验规则
const validate = (rules, value, callback) => {
const idCard = getFieldValue("idCard");
const accountCard = getFieldValue("accountCard");
if (!idCard && !accountCard) {
callback("身份证号或者账卡号必选其一");
} else {
callback();
}
};
// 选择其中一个聚焦时,另外一个校验提示消失
const handleValide = (e) => {
e.target.id === "idCard"
? setFields({
accountCard: {
value: getFieldValue("accountCard"),
errors: null,
},
})
: setFields({
idCard: {
value: getFieldValue("idCard"),
errors: null,
},
});
};
const formItemLayout = {
labelCol: { span: 12 },
wrapperCol: { span: 12 },
};