验证React-Draft-WYSIWYG输入

时间:2019-08-21 17:34:26

标签: javascript reactjs validation react-draft-wysiwyg

我正在表单中使用验证函数,该函数检查字段是否为。这适用于普通文本输入框,但不适用于React-Draft-WYSIWYG框。

我要检查WYSIWYG框是否为,如果是,请显示错误消息,即this.state.descriptionError

这是我的状态:

state = {
 name: "",
 description: [],
 nameError: "",
 descriptionError: "",
}

这是我的React-draft-WYSIWYG表单元素:

<Form>
 <Label>Description</Label>
  <Editor
   editorState={this.state.description}
   toolbarClassName="toolbarClassName"
   wrapperClassName="wrapperClassName"
   editorClassName="editorClassName"
   onEditorStateChange={this.onDescChange} />
    <div>
     {this.state.descriptionError}
    </div>
</Form>

我的验证功能如下:

validate = () => {
    let nameError = "";
    let descriptionError = "";

    if(!this.state.name) {                  // Checks if field is empty
      nameError = "Please enter a name";
    }

    if(this.state.description === "<p></p>↵") {          // The problem
      descriptionError = "Please enter a description";
    }

    if (nameError || descriptionError) {
      this.setState({nameError, descriptionError});

      return false;
    }
      return true;
  };

它与name字段一起正常工作,因为它等于一个空字符串。但是使用React-Draft-WYSIWYG,它不是字符串,因此我不确定将this.state.description设置为什么。

我们非常感谢您的帮助或建议,如果您需要更多详细信息,我可以迅速更新我的答案。

1 个答案:

答案 0 :(得分:0)

太晚了,但我希望它可以帮助某人!

您可以在编辑器的 state 变量中定义 2 个变量。

state = {
  isEditorTouched: false,
  isEditorEmpty: false,
  editorState: null,
}

在您的 onEditorStateChange 函数中添加 2 个条件:

onEditorStateChange = newEditorState => {
  let isEditorEmpty
  let isEditorTouched = this.state.isEditorTouched

  // If the length of editor's content !== 0, it means the editor has been touched
  if (this.state.editorState.getCurrentContent().getPlainText().length !== 0) {
    isEditorEmpty = false
    isEditorTouched = true
  } 
  
  //  if the editor is touched and length of editor === 0, it means the user removed the content, so the body is empty
  else if (this.state.isEditorTouched && this.state.editorState.getCurrentContent().getPlainText().length === 0) {
    isEditorEmpty = true
  }
  this.setState({
    ...this.state,
    isEditorEmpty,
    isEditorTouched,
    editorState: newEditorState,
  })
}

在您的 validation 函数中,您应该检查 isEditorEmpty 值。

if(this.state.isEditorEmpty) {
  // create your error description...
}

还要在您的 submit 表单函数上检查此值!