如何快速掌握forgJs:Rule单值验证与15种内置类型全覆盖清单
如何快速掌握forgJs:Rule单值验证与15种内置类型全覆盖清单
forgJs 是一款 JavaScript 轻量级对象验证库,通过 Rule 类即可对单个值做类型与规则校验,并内置 15 种常用数据类型(int、string、email、password、date 等),几行代码就能完成邮箱、密码、手机号这类高频验证场景,是前端表单校验和 Node.js 后端数据校验的好帮手。
🚀 为什么选择 forgJs?
- 轻量简单:API 只有
Rule(单值验证)和Validator(对象验证)两个核心类,新手 5 分钟上手 - 类型覆盖全:15 种内置类型 + 通用属性,绝大多数业务校验开箱即用
- 可扩展:支持多类型 OR/AND 组合,也能用
Rule.addCustom自定义新类型 - 报错友好:支持为每条 Rule 配置自定义错误信息
快速上手:3 行代码完成第一个验证
在项目目录执行安装命令:
npm i @cesium133/forgjs
创建一条整数规则并测试:
const { Rule } = require('@cesium133/forgjs');
const ageRule = new Rule({ type: 'int', min: 18, max: 99 });
ageRule.test(26); // true
ageRule.test(16); // false
💡 如果只需要校验类型,可以直接传字符串:
new Rule('int')。
Rule 单值验证:核心用法
Rule 的构造函数接收两个参数(见 src/Rule/index.js):
- 规则对象:描述校验逻辑,其中
type是唯一必填项 - 错误信息:字符串或函数,校验失败时返回给调用方
调用 rule.test(值) 后返回 true / false,核心逻辑在 src/Rule/index.js 的 test 方法中。一个规则对象创建后可以重复使用,建议把常用规则抽成模块常量。
15 种内置类型全覆盖清单
所有类型注册在 src/testFunctions/types/index.js,按用途分为四类:
| 分类 | 内置类型 | 典型用途 |
|---|---|---|
| 数字类 | int / float / number |
年龄、价格、版本号 |
| 字符串类 | string / password / email / url |
昵称、密码、邮箱、链接 |
| 基础结构类 | boolean / date / array / function |
开关、日期、列表、回调 |
| 字符串增强类 | string-int / string-float / string-date / string-boolean |
手机号、字符串日期等"长得像"的类型 |
字符串增强类会自动把值转成对应类型再校验,比如手机号通常就是 string-int(字符串形式的整数)。
各类型参数速查
数字类型:int / float / number
三者参数一致,区别只在类型判断(定义见 src/testFunctions/primitives.js):
min/max:最小值、最大值equal:必须等于某个值
字符串类型:string
minLength/maxLength:长度上下限equal:精确匹配match:正则表达式notEmpty:不能为空
邮箱与链接:email / url
两者继承 string 的全部参数,额外支持函数式断言(实现见 src/testFunctions/types/email.js 和 src/testFunctions/types/url.js):
const emailRule = new Rule({
type: 'email',
user: user => user === 'dedede',
domain: d => ['gmail', 'outlook', 'yahoo'].indexOf(d) !== -1,
});
密码强度:password
密码类型是业务中使用频率最高的类型,在 string 参数之外还支持(源码 src/testFunctions/types/password.js):
uppercase:至少包含 n 个大写字母numbers:至少包含 n 个数字specialChars:至少包含 n 个特殊字符matchesOneOf:数组中至少命中一个matchesAllOf:数组中必须全部命中
布尔、日期、数组与函数
| 类型 | 专属参数 | 说明 |
|---|---|---|
boolean |
toBe |
必须等于指定布尔值 |
date |
after / before / between / equal |
日期区间校验 |
array |
of / length / notEmpty |
of 可对每个元素应用子规则 |
function |
result: { of, toBe } |
用 of 值调用函数,用 toBe 规则校验返回值 |
array 的 of 参数可以直接传一条 Rule,实现"数组每一项都必须是字符串"这类校验:
new Rule({ type: 'array', of: new Rule({ type: 'string' }) });
字符串增强类型:string-int 等 4 兄弟
它们同时拥有 string 和被增强类型 的全部参数,先校验"是不是字符串",再把值转换后按目标类型校验(转换逻辑见 src/testFunctions/types/string-int.js)。
const phoneRule = new Rule({
type: 'string-int',
minLength: 10,
maxLength: 10,
match: /0(7|6).*?/,
});
多类型组合:OR 与 AND 一次搞定
type 字段支持用 |(或)和 &(与)组合多个类型,解析逻辑在 src/Rule/index.js:
new Rule({ type: 'int|float|number' }); // 任一类型通过即可
new Rule({ type: 'int&number' }); // 必须同时满足
这对"兼容多种输入格式"的场景非常实用,比如用户输入的年龄可能是 26、26.0 或字符串 "26"。
通用属性:optional、custom、oneOf
每种类型都自动附带三个通用属性(注册代码见 src/testFunctions/index.js):
optional:设为true时,undefined值直接通过,适合选填字段oneOf:值必须来自给定数组,例如oneOf: ['a', 'b']custom:编写完全自定义的校验函数,还可以拿到当前path和整个被校验对象,方便做跨字段联动校验
new Rule({
type: 'int',
min: 18,
optional: true,
custom: (age, path, obj) => age >= obj.minAge,
});
友好的错误提示:为每条 Rule 配置报错
创建 Rule 时第二个参数就是错误信息,支持字符串或函数:
const ageRule = new Rule(
{ type: 'int', min: 18, max: 99 },
'age must be integer and between 18 and 99'
);
getErrors 会把失败字段的错误信息收集成数组(实现见 src/Rule/index.js),可以直接渲染到表单上。
从 Rule 到 Validator:单值验证升级为对象验证
单条 Rule 解决一个字段,Validator 则负责"一个对象的所有字段",两者可无缝嵌套:
const v = new Validator({
age: new Rule({ type: 'int', min: 18 }),
email: emailRule,
password: passwordRule,
});
v.test({ age: 26, email: 'a@gmail.com', password: 'ad1_A@@Axs' }); // true
v.getErrors({ age: 16, dateOfBirth: 123 });
// ['age must be integer and between 18 and 99', 'date must be a date']
它还提供了 testAll 方法批量校验数组中的多个对象,返回第一个不合法项的下标(见 src/Validator/index.js)。
⚠️ 注意:
Validator要求字段与规则一一对应,对象中出现规则未声明的字段会被getErrors报告为xxx is unexpcted。
自定义新类型:Rule.addCustom
内置类型不够用?用 Rule.addCustom 就能注册全新的类型,之后可以像内置类型一样使用:
Rule.addCustom('customInteger', {
min: (val, min) => val - min > 0,
max: (val, max) => val - max < 0,
equal: (val, equal) => val === equal,
type: val => Number.isInteger(val) && val > 0 && val < 100,
});
new Rule({ type: 'customInteger', min: 10 }).test(11); // true
⚠️ 常见陷阱与最佳实践
- string-date 的时区陷阱:forgJs 会把字符串值转换后交给校验函数,
'2019-11-01'与new Date(2019, 10, 1)可能相差 1 小时(受本地时区影响),比较日期字符串时建议带上时间部分(如'2019-11-01T00:00') - 规则写错会立即抛错:创建 Rule 时如果
type不存在或参数不被支持,构造函数就会抛出类似`int` doesn't have "xxx" test!的错误——这是好事,能在开发阶段就暴露问题(校验逻辑见 src/Rule/index.js) - 规则对象可复用:Rule 创建后多次
test不会重复计算,公共规则建议抽成常量 - 多字段联动用 custom:需要跨字段判断(如"结束时间晚于开始时间")时,优先用
custom函数拿到完整对象处理
完整示例可以阅读 README.md,自动化测试用例覆盖了每种类型,参考 test/Rule/rule.test.js 与 test/Validator/Validator.test.js。
结语
forgJs 用 Rule + Validator 两个类就构建了完整的验证体系:Rule 负责单值验证,15 种内置类型覆盖绝大多数场景,多类型组合与自定义类型兜底。无论是前端表单还是 Node.js 接口,几行代码就能把数据校验变得简单可靠。



