
本文介绍如何使用 Formik 和 Yup 实现基于数组字段值的条件验证。针对 lessonType 数组包含特定值时,要求其他字段(如 videoFile 或 documentFile)必须存在的场景,提供了详细的 Yup 验证方案,并给出了代码示例,帮助开发者构建更健壮的表单验证逻辑。
在使用 Formik 和 Yup 构建表单时,经常会遇到需要根据某些字段的值来进行条件验证的情况。当需要基于数组字段的值进行验证时,情况会变得稍微复杂一些。本文将详细介绍如何使用 Yup 的 when 方法,结合 test 方法,来实现基于数组字段值的条件验证。
场景描述
假设我们有一个课程模块的表单,每个模块包含多个课程。每个课程都有一个 lessonType 字段,它是一个字符串数组,表示课程的类型(例如:"video", "document")。我们需要实现以下验证逻辑:
解决方案
我们可以使用 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"),
})代码解释
lessonType.test('file-test', 'File required', function (value) { ... }): 这是 Yup 的 test 方法,用于添加自定义的验证逻辑。
const { videoFile, documentFile } = this.parent;: 在验证函数中,this.parent 指向当前课程对象。我们可以使用它来访问 videoFile 和 documentFile 字段的值。
if (value.includes('video') && (!videoFile || videoFile.length === 0)) { ... }: 如果 lessonType 数组包含 "video",并且 videoFile 为空或长度为 0,则验证失败。this.createError 方法用于创建自定义的错误消息。
if (value.includes('document') && (!documentFile || documentFile.length === 0)) { ... }: 如果 lessonType 数组包含 "document",并且 documentFile 为空或长度为 0,则验证失败。
videoFile: Yup.mixed(), documentFile: Yup.mixed(),: 将 videoFile 和 documentFile 定义为 Yup.mixed() 类型,表示它们可以是任何类型。
注意事项
总结
通过使用 Yup 的 test 方法,我们可以轻松地实现基于数组字段值的条件验证。这种方法可以帮助我们构建更健壮的表单验证逻辑,并提供更好的用户体验. 关键在于理解 this.parent 的作用,它可以让我们访问当前对象中的其他字段,从而进行更复杂的验证。
以上就是Formik + Yup:基于数组字段值的条件验证的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号