antd的form表单中两项必选其中一项,同时校验效果的红星(*)和校验提示信息跟随一个的选择,另外一个消失(以input为例)

本文以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 },
  };

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值