输入验证 - 提交没有任何值的反应表单

Input validation - react form submitting without any values

我遇到了一个输入验证问题,允许表单在没有添加任何 selectorValue 的情况下提交。我的支票似乎只检查 textarea 中的输入,但不考虑按下的添加按钮。

这里 sandbox 重现了这个问题。

我正在使用 Semantic-ui-react,所以我的 <Form.Field /> 看起来像这样:

<Form.Field required>
  <label>Selector Values:</label>
  <TextArea
    type="text"
    placeholder="Enter selector values 1-by-1 or as a comma seperated list."
    value={this.state.selectorValue}
    onChange={this.handleSelectorValueChange}
    required={!this.state.selectorValues.length}
  />
  <Button positive fluid onClick={this.addSelectorValue}>
    Add
  </Button>
  <ul>
    {this.state.selectorValues.map((value, index) => {
      return (
        <Card>
          <Card.Content>
            {value}
            <Button
              size="mini"
              compact
              floated="right"
              basic
              color="red"
              onClick={this.removeSelectorValue.bind(this, index)}
            >
              X
            </Button>
          </Card.Content>
        </Card>
      );
    })}
  </ul>
</Form.Field>

所以在上面,<TextArea> 有一个必需的属性:!this.state.selectorValues.length。这只是检查 textarea 中的输入,它应该在允许表单提交之前检查是否已通过按 Add 按钮添加了值。

在您的 addSelectorValue 中添加一个检查以查看 this.state.selectorValue 它是否不为空,如果它只是 return,这将防止向 selectorValues[ 添加空值=17=]

addSelectorValue = e => {
    e.stopPropagation();
    e.preventDefault();

    if (!this.state.selectorValue) return;
    //continue if this.state.selectorValue has a value
};

在提交之前添加检查以查看 this.selectorValues 是否为空,如果是,请关注 textarea。

为了聚焦,我们需要先创建一个对文本区域的引用。

创建一个ref 附加到 dom 元素

textareaRef = React.createRef();

// will use our ref to focus the element
focusTextarea = () => {
  this.textareaRef.current.focus();
}

handleSubmit = () => {
  const { selectorValues } = this.state;
  if (!selectorValues.length) {
    // call our focusTextarea function when selectorValues is empty
    this.focusTextarea();
    return;
  }
  this.setState({ submittedSelectorValues: selectorValues });
};

// attach our ref to Textarea
<Textarea ref={this.textareaRef} />

经过一些搜索...required道具仅用于装饰目的 - 在字段标签中添加星号。

它没有表单验证。您需要一个单独的解决方案 - 尝试 formik 或在提交处理程序中设置一些条件。

具有 yup 验证模式的 Formik plays nicely - 适用于更复杂的动态需求。