【问题标题】:Validation of draft-js EditorState via yup in Formik通过 Formik 中的 yup 验证 Draft-js EditorState
【发布时间】:2019-02-08 01:48:20
【问题描述】:

我使用 Draft-js with Formikyup 来验证 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 的错误,还是我错误地使用了 yup

其他信息:

在 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

【问题讨论】:

  • 好问题!我今天刚刚尝试这样做。 Snap 我以为我可以通过draft-js-export-html 运行它,但它给了我这个例外。 TypeError: this.contentState.getBlocksAsArray is not a functionat MarkupGenerator.generate (stateToHTML.js:212)at stateToHTML (stateToHTML.js:579)
  • 很奇怪不是吗。使用手动验证功能可以正常工作(使用您的示例代码)const validation = ({ values }) => {const errors = {};if (!values.draftJSfield.getCurrentContent().hasText()) {errors.draftJSfield ='fill in draftJSfield';}return errors;};
  • @Buswell 毕竟我也使用了手动验证。仍然...想知道这里发生了什么!

标签: draftjs formik yup


【解决方案1】:

这适用于我的版本 0.10.5:

value._editorState.getCurrentContent().hasText()

【讨论】:

    【解决方案2】:

    这对我有用 Formik#1.5.7yum#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.'),
    

    而且我还必须做一些其他技巧来触发 Yum 的触摸对象和字段集。

    onChange={(field, value) => {
        setFieldValue(field, value)
    }}
    onFocus={(field) => {
        setFieldTouched(field)
    }}
    

    【讨论】:

    • 设置字段在聚焦技巧对我的验证有效。
    猜你喜欢
    • 2019-09-29
    • 2020-12-06
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2022-01-17
    • 2023-01-13
    相关资源
    最近更新 更多