Validation of draft-js EditorState via yup in Formik

Viewed 1948

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 Answers

This works for me with version 0.10.5:

value._editorState.getCurrentContent().hasText()

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