как применить валидацию в draftjs

У меня есть форма, которая включает электронную почту от, тему и текст, в котором используются черновики для редактора форматированного текста. Я мог бы проверить другие поля, но как я могу проверить редактор draftjs. Когда я нажимаю на редактор для ввода, если он оставлен пустым, он должен отображать ошибку, в противном случае успех, как на прилагаемом снимке экрана.

Вот мой код

function FieldGroup({ validationState, ...props }) {
  console.log(props);
  return (
    <FormGroup validationState={validationState}>
      <ControlLabel>{props.label}</ControlLabel>
      <FormControl {...props} />
    </FormGroup>
  );
}

class EmailTemplate extends React.Component {
  state = {
    emailFrom: ''
  };

  handleChange = event =>
    this.setState({ [event.target.name]: event.target.value });
  render() {
    const { templateName, emailSubject, emailFrom } = this.state;
    return (
      <form>
        <FieldGroup
          id="formControlsText"
          name="emailFrom"
          type="email"
          label="Email From"
          placeholder="Enter Email From"
          onChange={this.handleChange}
          validationState={emailFrom ? 'success' : 'error'}
          required
        />
        <AdminEditor />
        <Button type="submit">
          Submit
        </Button>
      </form>
    );
  }
}

export default EmailTemplate;


render() {
  const { editorContent, contentState, editorState } = this.state;
  return (
    <div>
      <Editor
        editorState={this.state.editorState}
        initialContentState={rawContentState}
        wrapperClassName="home-wrapper"
        editorClassName="home-editor"
        onEditorStateChange={this.onEditorStateChange}
        toolbar={{
          history: { inDropdown: true },
          inline: { inDropdown: false },
          list: { inDropdown: true },
          link: { showOpenOptionOnHover: true },
          textAlign: { inDropdown: true },
          image: { uploadCallback: this.imageUploadCallBack }
        }}
        onContentStateChange={this.onEditorChange}
        placeholder="write text here..."
        spellCheck
      />
    </div>
  );
}

введите здесь описание изображения


person pythonBeginner    schedule 24.05.2017    source источник


Ответы (2)


Вы можете использовать onBlur и onFocus события мыши в draft.js.

  • onBlur handle будет проверять содержимое редактора, когда пользователь покидает редактор и щелкает в другом месте. если содержимое редактора пусто, то в состоянии editorValidated устанавливается значение false.

  • onFocus дескриптор всегда устанавливает editorValidated как истину. Таким образом, когда пользователь снова начинает печатать, ошибки не возникает.

в компоненте Editor вы можете использовать editorValidated, чтобы добавить свой собственный стиль с помощью классов css.

    function FieldGroup({ validationState, ...props }) {
      console.log(props);
      return (
        <FormGroup validationState={validationState}>
          <ControlLabel>{props.label}</ControlLabel>
          <FormControl {...props} />
        </FormGroup>
      );
    }

    class EmailTemplate extends React.Component {
      state = {
        emailFrom: '',
        editorValidated:true,
      };

      handleChange = event =>
        this.setState({ [event.target.name]: event.target.value });
      render() {
        const { templateName, emailSubject, emailFrom } = this.state;
        return (
          <form>
            <FieldGroup
              id="formControlsText"
              name="emailFrom"
              type="email"
              label="Email From"
              placeholder="Enter Email From"
              onChange={this.handleChange}
              validationState={emailFrom ? 'success' : 'error'}
              required
            />
            <AdminEditor />
            <Button type="submit">
              Submit
            </Button>
          </form>
        );
      }
    }

    export default EmailTemplate;


    render() {
      const { editorContent, contentState, editorState } = this.state;
      return (
        <div>
          <Editor
            editorState={this.state.editorState}
            initialContentState={rawContentState}
            wrapperClassName="home-wrapper"
            editorClassName=`home-editor ${(this.state.editorValidated)?'validated','not-validated'}`
            onEditorStateChange={this.onEditorStateChange}
            toolbar={{
              history: { inDropdown: true },
              inline: { inDropdown: false },
              list: { inDropdown: true },
              link: { showOpenOptionOnHover: true },
              textAlign: { inDropdown: true },
              image: { uploadCallback: this.imageUploadCallBack }
            }}
            onFocus={()=>{this.setState({editorValidated:true})}}
            onBlur={()=>{this.setState({editorValidated:(this.state.editorState.getCurrentContent().getPlainText()!='')})}}
            onContentStateChange={this.onEditorChange}
            placeholder="write text here..."
            spellCheck
          />
        </div>
      );
    }
person Ramiz Ansari    schedule 07.01.2020

Вы можете использовать editorState.getCurrentContent().hasText(), чтобы проверить, ввел ли пользователь какой-либо текст в редакторе, и соответствующим образом применить свой стиль.

person Samuel Adafia    schedule 15.12.2020