reactjs - 是的,对数组下的对象进行验证
问题描述
我正在使用 Formik + Yup 创建带有验证的表单。我有以下初始值。
const initialValue = {
title: '',
schedules: [
{
maxGame: '',
bookingDuration: [],
reservationSlots: [
{
from: null,
to: null,
increment: '',
pricePerHours: [
{
guest: '',
price: ''
}
],
pricePerGame: [
{
type: 'Child',
price: ''
}
]
}
]
}
]
};
我当前的 yup 架构:
const schema = {Yup.object().shape({
title: Yup.string()
.min(2, 'Must be 2 characters or more')
.required('Title is required'),
schedules: Yup.array().of(
Yup.object().shape({
bookingDuration: Yup.array().when('maxGame', {
is: '',
then: Yup.array().min(1, 'Booking Duration is required'),
otherwise: Yup.array()
}),
maxGame: Yup.number().when('bookingDuration', {
is: (bookingDuration) => bookingDuration.length === 0,
then: Yup.number()
.min(1, 'Max Game must be greater than zero')
.required('Max Game is required either fill booking duration'),
otherwise: Yup.number()
}),
reservationSlots: Yup.array().of(
Yup.object().shape({
from: Yup.date().typeError('Invalid Time'),
to: Yup.date().typeError('Invalid Time'),
increment: Yup.string().required('Time Increment is required'),
pricePerGame: Yup.array().of(
Yup.object().shape({
type: Yup.string(),
price: Yup.string()
.when(['type'], {
is: (type) => type,
then: Yup.string().required('Price is required'),
}),
})
),
},
)
},
[['bookingDuration', 'maxGame']])
)
})
}
我想要以下验证:
- 需要 bookingDuration 和 maxGame 之一。
- 如果 bookingDuration.length > 0 则应要求 pricePerHours 的价格。
- 如果 pricePerHours 的价格已填写,则应该需要 bookingDuration。
- 如果 maxGame !== '' 那么 pricePerGame 的价格应该是必需的。
- 如果 pricePerGame 的价格被填满,那么 maxGame 应该是必需的。
我可以申请没有。1 验证,但其余无法应用验证。你能帮我解决这个问题吗?
解决方案
推荐阅读
- rust - 编辑文本文件时出现“错误的文件描述符”错误
- r - R DT 数据表格式Signif,没有科学记数法和逗号
- php - 在 php 类构造函数中将数组元素添加到 $this
- jestjs - 如何等待测试库中没有发生的事情?
- django - 防止 Django LDAP 插件在数据库中创建用户
- python - python中的numpy.str_错误预处理文本
- plot - 如何在 Julia 中叠加两个图
- javascript - 在 JavaScript 中对字符串数组进行排序
- quantmod - get.symbols 正在返回“缺少参数 conn,没有默认值”?
- json - ReactJS 从 Grails 获取 JSON