how to apply validation in draftjs

Viewed 1880

I have a form which includes email from, subject and text which uses drafts for rich text editor. I could validate other fields but how can i validate draftjs editor. When i click on editor to type, if it is left empty, it should show the error otherwise success like the one in attached screenshot.

Here is my code

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

enter image description here

2 Answers

You can use editorState.getCurrentContent().hasText() to check if the user has entered any text in the editor and apply your styling accordingly.

You can use onBlur and onFocus mouse event of draft.js.

  • onBlur handle will check for content of editor when user leave the editor and click somewhere else. if editor content is empty then it set editorValidated as false in state.

  • onFocus handle will always set editorValidated as true. So there is no error when user starts typing again.

in Editor component you can use editorValidated to add your custom styling through css classes.

    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>
      );
    }
Related