Open abhsingh-panw opened 3 years ago
I use the "convertToRaw" method of draft-js.
It returns a object {"blocks":[{"key":"dh5e6","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}}
Then I just compare the "text" length
if object.blocks[0].text.trim().length === 0{
//don't submit
}
have you try this yourValue.getCurrentContent().hasText() ?
You can do something like this:
if(draftToMarkdown(convertToRaw(editorState.getCurrentContent())).trim() === ""){ return true; }
in The component Editor.js
import { useField } from "formik";
const [field, meta] = useField(props.name);
const error = meta.touched && meta.error;
I added bellow <Editor ... />
{meta.touched && meta.error && (
<FormHelperText>{error}</FormHelperText>
) }
In the page where I used the Editor
when click in the editor , the value will be by default <p></p>
and length 8 so the test of dirty ll be true
<EditorDraft
name="value"
style={{ maxHeight: '200px' }}
// when click in the editor , the value will be by default <p></p> and length 8
handleChange={v => {
if (v.length > 8) {
setFieldValue('value', v);
} else {
setFieldValue('value', '');
}
}}
defaultValue={values.value}
toolbar={{
options: [
'inline',
'blockType',
'fontSize',
'fontFamily',
'list',
'textAlign',
'colorPicker',
'remove',
'history',
],
}}
/>
This works for me const isEmpty = convertToRaw(editorValue.getCurrentContent()).blocks.every(b => b.text.trim() === '');
This works for me const isEmpty = convertToRaw(editorValue.getCurrentContent()).blocks.every(b => b.text.trim() === '');
Edit: Here is an easier way to validate if the editor has text or not
const hasText = editorState.getCurrentContent().hasText()
This returns a boolean
if (hasText) {
// ...
} else {
// ...
}
I tried this
const htmlContent = draftToHtml(convertToRaw(state.getCurrentContent()));
const isEmpty = convertToRaw(state.getCurrentContent()).blocks.every(b => b.text.trim() === "");
const hasText = state.getCurrentContent().hasText();
console.log("htmlContent:", htmlContent);
console.log("isEmpty:", isEmpty);
console.log("hasText:", hasText);
htmlContent: <p></p>
isEmpty: true hasText: false
- With clearing everything but style is applied
htmlContent:
isEmpty: true hasText: false
- With empty lines and spaces
htmlContent:
isEmpty: true hasText: true
so for my case isEmpty is what I need because I want to prevent the user from submitting empty lines/spaces only
copy all CSS properties from ../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css
paste in separate file react-draft-w.css
codesandbox
CSS selector is .rdw-editor-main { height: 30%; box-sizing: border-box; background-color: #1236ff; }
How I can validate WYSIWYG input box for empty and whitespace value?
codesandbox link
<EditorField />
component is a required form field. I want to submit this form, only if user has entered any value.Default value of field is