SunEditor In React - Validate Text Was Inputted?

Problem

I want to validate that a user has inputted actual text into the editor, ignoring html tags and whitespace.

Details

  • I'm using the ReactJS SunEditor Component
  • I'm using Typescript

Here's an example of the content when a user doesn't type in anything:

 <p><br>
</p>

and another

<p>&nbsp;</p>

Attempted Solutions

I've tried putting a regex in the onChange event, but it's pretty clunky and probably won't take into account all the different ways non-textual content is represented; I need a better way.

const regex = /(<([^>]+)>)/ig;

Vague Ideas

I see that the SunEditor javascript api has a utility method, onlyZeroWidthSpace that returns a boolean; it may work, but I don't see how I can access it. I'm using Typescript, so maybe there's an issue there?

Thanks for your help!

4 Answers

Hi I am the author of the SunEditor React Component. Please the core SunEditor instance can be accessed by attaching a ref to the SunEditor component (You can review this from the documentation). Also to get plane text (non-html text), Please use the getText method on the editor object. Example below:

editorRef.current.editor.getText()

Notice that editorRef is the ref attached to the SunEditor Component.

Here's a funky way of doing it that seems to work. Any other suggestions are quite welcome and invited.

 <SunEditor ... onChange={content => { const contentTestContainer = document.createElement('div'); contentTestContainer.innerHTML = content; const textContent = contentTestContainer.textContent; if (textContent) { props.getFieldHelpers('description').setValue(content); } }} />

All event handler is bind the core object.onChange

editor.onChange = (contents, core) => { // You can use the util object core.util.onlyZeroWidthSpace();
}
1

You can try this:

onBlur = {(e) => console.log(e.target.innerText)}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like