4

I'm using Draft-js with Formik with yup for validation of the Draft EditorState component.

I assumed I would be able to check that EditorState is not blank by using the following yup test:

//Each note has a string title and a body, which is a Draft EditorState
const validationSchema = yup.object().shape({
  title: yup.string(),
  body: yup.object()
    .test("has text", "Cannot save an empty note", (value) => {
      return value.getCurrentContent().hasText();  //boolean
  }),
})

However, I get the error:

Uncaught (in promise) TypeError: Cannot read property 'length' of undefined at yupToFormErrors (formik.esm.js:491) at formik.esm.js:174

Is this a bug with formik, or am I using yup incorrectly?

Other information:

Inside validationSchema, I get the following:

console.log(value.getCurrentContent().hasText())  //returns undefined
console.log(value.getCurrentContent())  //returns undefined

But inside an onChange handler for EditorState ('body' field) it works properly:

console.log(value.getCurrentContent().hasText())  //returns true or false
gatlanticus
  • 1,158
  • 2
  • 14
  • 28
  • Great question! I've just tried to do this today. Snap I thought I'd be able to run it through `draft-js-export-html` but it gives me this exception. `TypeError: this.contentState.getBlocksAsArray is not a function` `at MarkupGenerator.generate (stateToHTML.js:212)` `at stateToHTML (stateToHTML.js:579)` – Daniel Gent Sep 06 '18 at 14:52
  • 1
    So weird isn't it. Using a manual validation function it works fine (using your example code) `const validation = ({ values }) => {` `const errors = {};` `if (!values.draftJSfield.getCurrentContent().hasText()) {` `errors.draftJSfield =` `'fill in draftJSfield';` `}` `return errors;` `};` – Daniel Gent Sep 06 '18 at 15:08
  • @Buswell I also used manual validation after all. Still... would like to know what's going on here! – gatlanticus Sep 06 '18 at 20:06

2 Answers2

2

This works for me with version 0.10.5:

value._editorState.getCurrentContent().hasText()
Nick Day
  • 21
  • 2
1

This worked for me for Formik#1.5.7 and yum#0.27.0

Yup.object()
    .test(
        'has text',
        'Cannot save an empty note',
         value => value && value.blocks && value.blocks[0].text.length
    ).required('This field is required.'),

And also i had to do some other tricks to trigger touched object and field set of Yum.

onChange={(field, value) => {
    setFieldValue(field, value)
}}
onFocus={(field) => {
    setFieldTouched(field)
}}
Sercan VİRLAN
  • 113
  • 1
  • 4
  • 12