登录
首页 >  文章 >  前端

FormikYup数组条件验证详解

时间:2025-08-05 09:06:32 384浏览 收藏

还在为 Formik 表单中数组字段的条件验证而烦恼吗?本文针对使用 Formik 和 Yup 构建表单时,需要根据数组字段值进行条件验证的复杂场景,提供了详细的解决方案。通过 Yup 的 `test` 方法,结合 `this.parent` 访问同级字段,轻松实现诸如:当 `lessonType` 数组包含 "video" 时,`videoFile` 必须上传;包含 "document" 时,`documentFile` 必须上传等复杂逻辑。本文提供可直接使用的代码示例,助你快速构建更健壮、用户体验更佳的表单验证体系,避免无效数据提交,提升 Web 应用的质量。深入理解 `this.parent` 的用法,掌握 Yup 数组字段条件验证的核心技巧,让你的 Formik 表单验证更上一层楼!

Formik + Yup:基于数组字段值的条件验证

本文介绍如何使用 Formik 和 Yup 实现基于数组字段值的条件验证。针对 lessonType 数组包含特定值时,要求其他字段(如 videoFile 或 documentFile)必须存在的场景,提供了详细的 Yup 验证方案,并给出了代码示例,帮助开发者构建更健壮的表单验证逻辑。

在使用 Formik 和 Yup 构建表单时,经常会遇到需要根据某些字段的值来进行条件验证的情况。当需要基于数组字段的值进行验证时,情况会变得稍微复杂一些。本文将详细介绍如何使用 Yup 的 when 方法,结合 test 方法,来实现基于数组字段值的条件验证。

场景描述

假设我们有一个课程模块的表单,每个模块包含多个课程。每个课程都有一个 lessonType 字段,它是一个字符串数组,表示课程的类型(例如:"video", "document")。我们需要实现以下验证逻辑:

  • 如果 lessonType 数组包含 "video",则必须上传视频文件 (videoFile)。
  • 如果 lessonType 数组包含 "document",则必须上传文档文件 (documentFile)。

解决方案

我们可以使用 Yup 的 test 方法,在 lessonType 字段的验证规则中添加自定义的验证逻辑。test 方法允许我们编写 JavaScript 代码来执行验证,并根据验证结果返回 true (验证通过) 或 false (验证失败)。

以下是具体的代码示例:

import * as Yup from 'yup';

let validationSchema = Yup.object({
  modules: Yup.array(
    Yup.object({
      title: Yup.string()
        .required("A module title is required")
        .min(1, "A module title is required"),
      lessons: Yup.array(
        Yup.object({
          lessonTitle: Yup.string().required("A lesson title is required"),
          lessonType: Yup.array()
            .min(1, "Lesson type is required")
            .required("Lesson type is required")
            .test('file-test', 'File required', function (value) {
              const { videoFile, documentFile } = this.parent;
              if (value.includes('video') && (!videoFile || videoFile.length === 0)) {
                return this.createError({ message: 'Video file required when lesson type is video' });
              }
              if (value.includes('document') && (!documentFile || documentFile.length === 0)) {
                return this.createError({ message: 'Document file required when lesson type is document' });
              }
              return true;
            }),
          videoFile: Yup.mixed(),
          documentFile: Yup.mixed(),
        })
      ),
    })
  )
    .min(1, "You must add at least one module")
    .required("You must add at least one module"),
})

代码解释

  1. lessonType.test('file-test', 'File required', function (value) { ... }): 这是 Yup 的 test 方法,用于添加自定义的验证逻辑。

    • 'file-test':测试的名称,用于标识这个测试。
    • 'File required':默认的错误消息,如果验证失败,将显示此消息。
    • function (value) { ... }:验证函数。value 参数是 lessonType 数组的值。
  2. const { videoFile, documentFile } = this.parent;: 在验证函数中,this.parent 指向当前课程对象。我们可以使用它来访问 videoFile 和 documentFile 字段的值。

  3. if (value.includes('video') && (!videoFile || videoFile.length === 0)) { ... }: 如果 lessonType 数组包含 "video",并且 videoFile 为空或长度为 0,则验证失败。this.createError 方法用于创建自定义的错误消息。

  4. if (value.includes('document') && (!documentFile || documentFile.length === 0)) { ... }: 如果 lessonType 数组包含 "document",并且 documentFile 为空或长度为 0,则验证失败。

  5. videoFile: Yup.mixed(), documentFile: Yup.mixed(),: 将 videoFile 和 documentFile 定义为 Yup.mixed() 类型,表示它们可以是任何类型。

注意事项

  • 错误消息会显示在 lessonType 字段下方。如果需要将错误消息显示在 videoFile 或 documentFile 字段下方,则需要调整错误处理逻辑。
  • videoFile 和 documentFile 的类型可以根据实际情况进行调整。例如,如果它们是文件对象,则可以使用 Yup.mixed().test(...) 来验证文件类型和大小。
  • 可以根据实际需求添加更多的条件验证逻辑。

总结

通过使用 Yup 的 test 方法,我们可以轻松地实现基于数组字段值的条件验证。这种方法可以帮助我们构建更健壮的表单验证逻辑,并提供更好的用户体验. 关键在于理解 this.parent 的作用,它可以让我们访问当前对象中的其他字段,从而进行更复杂的验证。

到这里,我们也就讲完了《FormikYup数组条件验证详解》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>