forgJs嵌套对象验证实战:Validator处理深层结构与批量数据的方法

原创2026-10-15 09:48:061,325 阅读

forgJs嵌套对象验证实战:Validator处理深层结构与批量数据的方法

forgJs 是一个 JavaScript 轻量级对象验证库,其核心 Validator 类专为复杂对象结构设计。本文以用户管理场景为例,实战讲解如何用 forgJs 为嵌套对象编写验证规则,以及如何用 testAll 和 getErrors 快速完成批量数据校验。

forgJs对象验证库:email 字段 Email rule 验证演示

快速上手:npm 一键安装步骤

安装只需一条命令:

npm i @cesium133/forgjs

forgJs 只有两个核心概念:

  • Rule:验证单个值,比如"年龄必须是 18~99 的整数";
  • Validator:把一组 Rule 挂到对象的字段上,验证整个对象。
const { Rule, Validator } = require('@cesium133/forgjs');

const vUser = new Validator({
  name: new Rule({ type: 'string', notEmpty: true }),
  age: new Rule({ type: 'int', min: 18, max: 99 }),
});

vUser.test({ name: 'Alice', age: 26 }); // true

实现细节可以参考 src/Rule/index.js 和 src/Validator/index.js。

嵌套对象验证:Validator 深层规则的 3 种写法

写法一:镜像嵌套(最常用)

规则对象的结构与数据"镜像"对应即可——凡是规则里是普通对象的位置,Validator 都会递归进入,逐层取字段值(实现在 src/Validator/util.js 的 traverse 与 getValFromPath):

const vProfile = new Validator({
  name: new Rule({ type: 'string', notEmpty: true }),
  profile: {
    email: new Rule({ type: 'email' }),
    password: new Rule({
      type: 'password',
      minLength: 8,
      uppercase: 1,
      numbers: 1,
    }),
    age: new Rule({ type: 'int', min: 18, max: 99 }),
  },
});

vProfile.test({
  name: 'Alice',
  profile: { email: 'alice@gmail.com', password: 'ad1_A@@Axs', age: 26 },
}); // true

forgJs嵌套对象验证:password 密码强度规则演示

写法二:用 of 校验"对象数组"

array 类型的 of 参数既可以是 Rule,也可以直接是一个 Validator,适合校验列表数据:

const userValidator = new Validator({
  name: new Rule('string'),
  age: new Rule('int'),
});

const vTeam = new Validator({
  members: new Rule({ type: 'array', of: userValidator, notEmpty: true }),
});

vTeam.test({ members: [{ name: 'Meee', age: 23 }] }); // true

更多用法见 test/Rule/array.test.js。

写法三:复用实例,规则与校验器分离

把常用 Rule 抽成常量,多个 Validator 共享,深层结构再多也不慌:

const stringIntPhone = new Rule({
  type: 'string-int',
  minLength: 10,
  maxLength: 10,
});

批量数据验证:用 testAll 一键定位异常项

收到一批数据时,用 testAll 逐条过同一个 Validator,它会返回第一条不合格数据的下标,全部通过则返回 -1:

const vSite = new Validator({
  name: new Rule({ type: 'string', notEmpty: true }),
  url: new Rule({
    type: 'url',
    protocol: prot => prot === 'https',
  }),
});

const sites = [
  { name: 'Docs', url: 'https://docs.example.com' },
  { name: 'Blog', url: 'http://blog.example.com' }, // 协议不合规
  { name: 'API',  url: 'https://api.example.com' },
];

vSite.testAll(sites); // 1 —— 第 2 条(下标 1)不合法

forgJs批量数据验证:url 字段协议与域名规则演示

💡 小提示:testAll 只报告"第一个坏点"。如果需要把所有问题一次性列出来,请配合下面的 getErrors 使用。

深层错误定位:getErrors 输出可读的错误信息

Rule 的第二个参数是错误定义,支持三种形式:字符串、(path, value) 函数、按规则键名映射的对象。嵌套字段出错时,错误信息会自动带上 profile.age 这样的完整路径,定位非常方便:

const vUser = new Validator({
  name: new Rule({ type: 'string', notEmpty: true }, 'name is required'),
  profile: {
    age: new Rule({ type: 'int', min: 18, max: 99 },
      (path, value) => `${path} must be 18-99, got: ${value}`),
  },
});

vUser.getErrors({ name: '', profile: { age: 16 } });
// ['name is required', 'profile.age must be 18-99, got: 16']

如果未提供错误定义,getErrors 会输出默认的 `路径 doesn't satisfy the 规则名 rule` 提示,错误生成逻辑见 src/Rule/util.js。

新手常见 4 个坑

  1. 数据里不能出现未声明的字段。Validator 会先做"字段集合检查",数据多出一个规则里没定义的 key,test 直接返回 false(见 test/Validator/Validator.test.js 的 extraValue 用例)。
  2. 缺字段只有声明 optional: true 才允许。否则 undefined 会直接判为不合法。
  3. testAll 返回的是下标,不是布尔值。-1 全过,0 表示第一条就挂了,注意区分。
  4. string-* 类型会自动转换。例如 string-int、string-date 会先把字符串 cast 成目标类型再验证,跨时区场景下 '2020-01-01' 与 '2020-01-01T00:00' 可能给出不同结果,编写日期规则时要留意。

forgJs对象验证:string-int 类型手机号 Custom rule 演示

总结:核心文件速查

文件 作用
src/Validator/index.js test / testAll / getErrors 入口
src/Validator/util.js 嵌套结构遍历与路径取值
src/Rule/index.js 单值规则与自定义类型扩展
src/testFunctions/index.js 内置类型(int、email、array…)实现
README.md 全部规则参数速查

掌握了"镜像嵌套 + of 校验对象数组 + testAll/getErrors 组合",forgJs 就能轻松应对绝大多数深层结构与批量数据验证场景 🚀

登录后查看全文
forgJs