react-component / form

React High Order Form Component(web & react-native)
http://react-component.github.io/form/
MIT License
1.81k stars 296 forks source link

How to test that a checkbox is checked? #202

Open Alexandre-T opened 6 years ago

Alexandre-T commented 6 years ago

When user is registering, I want to verify that the "I accept Terms of Service" checkbox is checked. But I am not able to do it. Is it an issue or did I done a mistake?

Here is some of my test:

         {...getFieldProps("read", {
            initialValue: read,
            rules:[{"required":true}],
            onChange,
            valuePropName: "checked"
          })}

         {...getFieldProps("read", {
            initialValue: read,
            rules:[{
              "type": "enum",
              "enum":[true],
              "required":true
            }],
            onChange,
            valuePropName: "checked"
          })}

No one is working. Below this is my (simplified) code: (I'm using reactstrap forms)

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>
}