
本文介绍了如何在使用Formik和Yup进行表单验证时,根据数组字段的值进行条件验证。核心在于利用Yup的test方法,结合this.parent访问同级字段,实现对lessonType数组中包含特定值时,对应文件字段是否存在的校验。
在使用Formik进行表单管理,并结合Yup进行数据验证时,经常会遇到需要根据某个字段的值,来决定是否需要验证其他字段的情况。当这个“某个字段”是一个数组时,处理起来会稍微复杂一些。本文将详细介绍如何使用Yup的test方法,来实现基于数组字段值的条件验证。
问题场景
假设我们有一个课程模块的表单,其中每个模块包含多个课程。每个课程可以有不同的类型,例如视频、文档等。我们需要验证,当课程类型包含“视频”时,必须上传视频文件;当课程类型包含“文档”时,必须上传文档文件。
解决方案
Yup提供了test方法,允许我们自定义验证逻辑。我们可以利用test方法,结合this.parent访问同级字段,来实现我们的需求。
示例代码
首先,定义我们的验证Schema:
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 && value.includes('video') && (!videoFile || videoFile.length === 0)) { return this.createError({ message: 'Video file required when lesson type is video' }); } if (value && 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: Yup.array().test(…): 我们对lessonType字段使用test方法,定义了一个名为file-test的自定义验证。function (value) { … }: test方法的参数是一个函数,value是当前字段的值,也就是lessonType数组。const { videoFile, documentFile } = this.parent;: this.parent指向当前lesson对象,通过解构赋值,我们可以方便地访问videoFile和documentFile字段。if (value.includes(‘video’) && (!videoFile || videoFile.length === 0)) { … }: 判断lessonType数组是否包含’video’,并且videoFile不存在或为空,如果满足条件,则调用this.createError创建一个错误。this.createError({ message: ‘Video file required when lesson type is video’ });: this.createError用于创建验证错误,message是错误信息。videoFile: Yup.mixed(), documentFile: Yup.mixed(),: 定义videoFile和documentFile的类型为mixed,表示可以是任意类型,这里可以根据实际情况定义为Yup.string()或者Yup.object()等。
注意事项
this.parent只能在test方法的回调函数中使用。错误信息会默认显示在lessonType字段下方,如果需要显示在对应的文件字段下方,需要自定义错误处理逻辑。需要确保videoFile和documentFile字段存在于Formik的值中,否则this.parent.videoFile和this.parent.documentFile会返回undefined。
总结
通过Yup的test方法,我们可以灵活地实现各种复杂的条件验证。关键在于利用this.parent访问同级字段,并结合JavaScript的逻辑判断,来决定是否需要创建验证错误。在实际项目中,可以根据具体的业务需求,调整验证逻辑和错误信息,以达到最佳的用户体验。
以上就是Formik与Yup:基于数组字段值的条件验证的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1511150.html
微信扫一扫
支付宝扫一扫