4
votes

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
2
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
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
@Buswell I also used manual validation after all. Still... would like to know what's going on here!ZG101

2 Answers

1
votes

This works for me with version 0.10.5:

value._editorState.getCurrentContent().hasText()
0
votes

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