【问题标题】:How to verify that the checkbox is checked with rc-forms package?如何验证复选框是否被 rc-forms 包选中?
【发布时间】:2019-03-05 02:29:06
【问题描述】:

当用户注册时,我想检查是否已阅读并接受 TOS(服务条款)。为此,我的表格上有一个复选框“我接受 TOS”

我正在使用rc-form package 来验证我的 reactstrap 表单,但我不知道如何验证(通过 rc-form)复选框是否被选中。有没有使用 rc-form 来避免手动测试的解决方案?

在此示例中,即使未选中 TOS 复选框,tosErrors 仍为空

onSubmit(e) {
  e.preventDefault();

  this.props.form.validateFields((error) => {
    if (!error) {
      const { register } = this.props;
      const { email, password, read } = this.state;

      //HERE IS A MANUAL TEST BECAUSE rules on checkbox are not working
      if (read) {
        register(email, password);
      }
    }
  });
}

render() {
  //...some code was removed because unuseful for stackoverflow question...
  const { getFieldProps, getFieldError, getFieldValue } = this.props.form;
  const tosErrors= getFieldError("read");

  return (
    <Form onSubmit={this.onSubmit}>
      //... some form elements ...
      <FormGroup check>
        <Col sm={{ size: 8, offset: 4 }}>
          <Label check>
            <Input
              type="checkbox"
              name="read"
              id="read"
              className={tosErrors ? "is-invalid" : ""}
              {...getFieldProps("read", {
                initialValue: read,
                rules:[{"required":true}], <==== THE RULES
                onChange,
                valuePropName: "checked"
              })}
            />
          </Label>
          // BELOW THIS IS ONE OF MY MANUAL TEST because tosErrors stay empty
          {getFieldValue("read") || <HelpBlock color={"danger"}>{t("validators:accept cgu")}</HelpBlock>}
        </Col>
      </FormGroup>
      ... SOME OTHER FORM ELEMENTS
    </Form>
}

rc-form 包正在使用async-validator

【问题讨论】:

    标签: reactjs validation rc-form


    【解决方案1】:

    render()之前向您的组件添加验证器功能:

    checkIsChecked = (rule, value, callback) => {
        if (value === false) {
            callback("You should agree with Terms of Service!");
        } else {
            callback();
        }
    }
    

    然后将具有此功能的验证器添加到rules

    rules: [{ required: true }, {
        validator: this.checkIsChecked,
    }],
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-07
      • 2011-04-04
      • 2019-03-16
      • 2018-09-24
      • 2018-03-23
      • 2017-06-24
      • 2013-01-25
      相关资源
      最近更新 更多