首页 > 解决方案 > 通过 Formik 中的 yup 验证 Draft-js EditorState

问题描述

我正在使用带有 Formik 的 Draft-js 和yup验证 Draft EditorState 组件。

我假设我可以通过使用以下 yup 测试来检查 EditorState 是否为空白:

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

但是,我收到错误:

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

这是formik的错误,还是我使用错误

其他信息:

在validationSchema 中,我得到以下信息:

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

但在 EditorState ('body' 字段)的 onChange 处理程序中,它可以正常工作:

console.log(value.getCurrentContent().hasText())  //returns true or false

标签: draftjsformikyup

解决方案


这适用于我的版本 0.10.5:

value._editorState.getCurrentContent().hasText()

推荐阅读