You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Superstruct实现依赖其他字段的自定义验证需求

使用Superstruct实现字段联动验证逻辑

需求概述

需要验证对象的fieldA和fieldB两个字段:

  • 字段类型为字符串或null
  • 验证通过条件:两者同时为长度≥1的有效字符串,或同时为null/空字符串
  • 验证失败条件:一个为有效字符串,另一个为null/空字符串

实现步骤

  1. 安装Superstruct
npm install superstruct
  1. 编写验证逻辑
    通过superstruct的基础类型定义+自定义refine验证来实现:
import { struct, nullable, string, refine } from 'superstruct';

// 定义基础字段类型:允许字符串(含空)或null
const BaseStruct = struct({
  fieldA: nullable(string()),
  fieldB: nullable(string()),
});

// 添加自定义联动验证逻辑
const ValidatedStruct = refine(BaseStruct, 'FieldConsistency', (value) => {
  // 判断单个字段是否为有效状态(非null且长度≥1)
  const isValidField = (field) => typeof field === 'string' && field.length >= 1;
  
  const isAValid = isValidField(value.fieldA);
  const isBValid = isValidField(value.fieldB);

  // 两个字段状态一致则通过,否则返回错误信息
  return isAValid === isBValid || 'fieldA和fieldB必须同时为有效字符串(长度≥1),或同时为null/空字符串';
});

测试示例

验证通过的场景

// 场景1:两者均为有效字符串
const validCase1 = { fieldA: 'aaa', fieldB: 'bb' };
console.log(ValidatedStruct.is(validCase1)); // 输出:true

// 场景2:两者均为无效状态(空字符串+null)
const validCase2 = { fieldA: '', fieldB: null };
console.log(ValidatedStruct.is(validCase2)); // 输出:true

验证失败的场景

// 场景3:fieldA为空字符串,fieldB为有效字符串
const invalidCase1 = { fieldA: '', fieldB: 'bb' };
try {
  ValidatedStruct(invalidCase1);
} catch (error) {
  console.error(error.message); // 输出:fieldA和fieldB必须同时为有效字符串(长度≥1),或同时为null/空字符串
}

// 场景4:fieldA为null,fieldB为有效字符串
const invalidCase2 = { fieldA: null, fieldB: 'bb' };
try {
  ValidatedStruct(invalidCase2);
} catch (error) {
  console.error(error.message); // 输出:相同错误信息
}

逻辑说明

  • 基础结构体BaseStruct确保字段只能是字符串(包括空字符串)或null,过滤其他非法类型
  • refine方法添加的自定义验证,通过对比两个字段的“有效状态”是否一致,实现联动校验
  • 错误提示清晰明确,便于定位问题

内容的提问来源于stack exchange,提问作者yo_nas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:56:12