如何在React-hook-form中用Yup验证日期数组,仅缺第二个日期时报错?
自定义日期数组验证方案
你之前用的Array().min(2).required()不生效的原因是:当数组存在第一个元素、第二个元素为空(null/undefined/空字符串)时,数组长度依然是2,min(2)仅校验数组长度,不会判断元素是否实际有值,所以无法触发你需要的错误提示。
针对Selected_date和Completion_date的验证需求,我们可以用自定义校验函数来实现精准判断:
核心逻辑
仅当以下场景触发错误:
- 数组第一个元素有值(非空、非undefined、非null)
- 数组第二个元素为空(空字符串、undefined、null)
其余场景(数组全空、两个元素都有值)均通过验证
代码实现(以Joi为例)
const schema = Joi.object({ // 处理Selected_date字段 Selected_date: Joi.array() .custom((value, helpers) => { // 校验第一个日期存在但第二个缺失的情况 const hasStartDate = value[0] !== undefined && value[0] !== null && value[0] !== ''; const noEndDate = value[1] === undefined || value[1] === null || value[1] === ''; if (hasStartDate && noEndDate) { return helpers.error('any.invalid', { message: 'Second Date is required' }); } return value; }) .messages({ 'any.invalid': '{{#message}}' }), // 处理Completion_date字段 Completion_date: Joi.array() .custom((value, helpers) => { const hasSourceDate = value[0] !== undefined && value[0] !== null && value[0] !== ''; const noTargetDate = value[1] === undefined || value[1] === null || value[1] === ''; if (hasSourceDate && noTargetDate) { return helpers.error('any.invalid', { message: 'Second Date is empty' }); } return value; }) .messages({ 'any.invalid': '{{#message}}' }) });
验证说明
- 当
Selected_date仅填了起始日期、未填结束日期时,抛出Second Date is required错误 - 当
Completion_date仅填了源日期、未填目标日期时,抛出Second Date is empty错误 - 数组全空或两个日期都填写时,验证通过
内容的提问来源于stack exchange,提问作者Prasad Hari
相关产品推荐
相关产品推荐

