# @chantouchsek/validatorjs 中文文档

规范地址：https://npmcn.com/package/%40chantouchsek/validatorjs/

版本：2\.3\.0
npm 元数据更新时间：2026-10-17T07:45:13.981Z
中文译文更新时间：2026-11-09T10:46:11.998Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40chantouchsek/validatorjs
原文对照：https://npmcn.com/package/%40chantouchsek/validatorjs/?lang=original
项目主页：https://github.com/chantouchsek/validatorjs#readme
源码仓库：https://github.com/chantouchsek/validatorjs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：926 kB，13 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：^12\.20\.0 \|\| \>=14\.13\.0
- 运行依赖：1 个
- peer 依赖：libphonenumber-js ^1\.13\.15
- 首次发布：2020-07-23T15:33:01.121Z
- 最新版本发布：2026-10-17T07:45:13.828Z
- 近 30 天下载量：2891（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：57（近 12 个月 5 个）

## 中文简介

校验器.js库使得JavaScript中的数据验证在浏览器和Node.js中都非常容易.

## 安装

```sh
npm install @chantouchsek/validatorjs
```

也可以使用：`pnpm add @chantouchsek/validatorjs`、`yarn add @chantouchsek/validatorjs`、`bun add @chantouchsek/validatorjs`

## README

# 验证器Js

[![ci](https://github.com/chantouchsek/validatorjs/actions/workflows/ci.yml/badge.svg)](https://github.com/chantouchsek/validatorjs/actions/workflows/ci.yml) [![Latest Version on NPM](https://img.shields.io/npm/v/@chantouchsek/validatorjs.svg?style=flat-square)](https://npmjs.com/package/@chantouchsek/validatorjs) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://npmcn.com/package/%40chantouchsek/validatorjs/LICENSE) [![npm](https://img.shields.io/npm/dt/@chantouchsek/validatorjs.svg?style=flat-square)](https://npmjs.com/package/@chantouchsek/validatorjs) [![npm](https://img.shields.io/npm/dm/@chantouchsek/validatorjs.svg?style=flat-square)](https://npmjs.com/package/@chantouchsek/validatorjs) [![code style](https://antfu.me/badge-code-style.svg)](https://github.com/antfu/eslint-config)

校验器Js库使得JavaScript中的数据校验在浏览器和Node.js中都非常容易. 这个图书馆是 从 [验证器Js](https://github.com/mikeerickson/validatorjs) 以打字符重写以添加更多规则和 特性.

## 为什么使用验证器Js?

-   在浏览器和节点都工作.
-   可读和可申报审定规则.
-   有多语种支持的错误消息 .
-   CommonJS/浏览支持.
-   ES6支持.
-   重写为打字符

## 安装

### 使用 pnpm

```bash
pnpm add @chantouchsek/validatorjs
```

### 使用 npm

```bash
npm install @chantouchsek/validatorjs
```

### 使用线条

```bash
yarn add @chantouchsek/validatorjs
```

### 基本用途

```ts
import { Validator } from '@chantouchsek/validatorjs'

const data = { email: 'ada@example.com' }
const rules = { email: 'required|email' }
const options = { customAttributes: { email: 'Email address' } }
const validation = new Validator(data, rules, options)
validation.passes() // => true
```

**数据** {对象} - 您想要验证的数据

**规则** {对象} - 验证规则

**选项** {Object} - 可选验证和信件配置

-   选项
    -   语言?: LangTypes 选择捆绑的语言
    -   确认反向 ? : boolean QQ 可选显示确认字段的错误消息而不是密码
    -   自定义消息 ?: 记录 < string, any > QQ 可选自定义错误消息以返回
    -   自定义属性 ?: 记录 <string, any > QQ 可选自定义属性名称以返回
    -   默认属性Name : 部分 < 记录 < LangTypes, string \* \* \* \* \* 替换: 选定地块的属性

下面的例子使用 TypeScript 和软件包的名称 `Validator` 输出。 同步 `passes()` 财务报告和审定财务报表 `fails()` 返回布尔; 基于召回的验证返回 `void`。 。 。 . `passesAsync()` 总是返回 `Promise<boolean>` 无论是哪种规则. 每次验证运行都会取代实例之前的错误和错误计数.

#### 例1 - 通过验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const data = {
  age: 28,
  email: 'johndoe@gmail.com',
  name: 'John',
}

const rules = {
  age: 'min:18',
  email: 'required|email',
  name: 'required',
}

const validation = new Validator(data, rules)

validation.passes() // => true
validation.fails() // => false
```

将审定规则适用于 _数据_ 对象,使用相同的对象密钥名称 _规则_ 对象.

#### 例2 - 未能验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validation = new Validator(
  {
    email: 'not an email address.com',
    name: 'D',
  },
  {
    email: 'required|email',
    name: 'size:3',
  },
)

validation.fails() // => true
validation.passes() // => false

// Error messages
validation.errors.first('email') // => 'The email format is invalid.'
validation.errors.get('email') // => ['The email format is invalid.']
validation.errors.has('name') // => true
validation.errorCount // => 2
validation.errors.all() // => { email: ['The email format is invalid.'], name: ['The name must be 3 characters.'] }
```

#### 例3 - 有默认属性名称

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validation = new Validator(
  {
    email: 'not an email address.com',
    name: 'D',
  },
  {
    email: 'required|email',
    name: 'size:3',
  },
  {
    locale: 'ja',
    defaultAttributeName: {
      en: '',
      ja: 'この項目',
    },
  },
)

validation.fails() // => true
validation.passes() // => false

// Error messages
validation.errors.first('email') // => 'この項目は正しいメールアドレスを入力してください。'
```

### 有时需要和存在的可选字段

例如: `email` 跳过缺失, `undefined`, (中文(简体) ), `null`空字符串 数值。 添加 `required` 拒绝他们. `sometimes` 仅当 缺少密钥; 明确提供的空值仍在运行 `required`。 。 。 . `present` 目前拒绝丢失的密钥和 `undefined`,但接受 `null`, (中文(简体) ), 空字符串,零,假,和空数组.

```ts
import { Validator } from '@chantouchsek/validatorjs'

new Validator({}, { email: 'email' }).passes() // => true
new Validator({ email: '' }, { email: 'email' }).passes() // => true
new Validator({}, { email: 'required|email' }).passes() // => false
new Validator({}, { email: 'sometimes|required|email' }).passes() // => true
new Validator({ email: '' }, { email: 'sometimes|required|email' }).passes() // => false
new Validator({ email: undefined }, { email: 'sometimes|required' }).passes() // => false
new Validator({ email: null }, { email: 'present' }).passes() // => true
new Validator({ email: undefined }, { email: 'present' }).passes() // => false
new Validator({}, { email: 'present' }).passes() // => false
new Validator({ count: 0, enabled: false }, { count: 'required', enabled: 'required' }).passes() // => true
new Validator({ tags: [] }, { tags: 'required|array' }).passes() // => false
```

`required` 检查非空白字符串的表示式, 所以零和假的通过 空数组失败 。 纵使空出,阵列仍然运行普通规则. 校验不会强制输入类型:一个数字字符串可以通过 `numeric` 时 在返回的数据中保留字符串.

### 嵌入式规则

嵌入式物体也可以被验证. 有两种方式来宣布嵌入物的验证规则. 第一个办法 即以相应的嵌入式物体结构声明验证规则,以反映数据。 第二条路 以平分键名宣布验证规则。 例如,验证下列数据:

```ts
import { Validator } from '@chantouchsek/validatorjs'

const data = {
  bio: {
    age: 28,
    education: {
      primary: 'Elementary School',
      secondary: 'Secondary School',
    },
  },
  name: 'John',
}
// Either nested rules or flattened paths can validate this data.
const nested = {
  bio: {
    age: 'min:18',
    education: {
      primary: 'string',
      secondary: 'string',
    },
  },
  name: 'required',
}

// OR

const flattened = {
  'bio.age': 'min:18',
  'bio.education.primary': 'string',
  'bio.education.secondary': 'string',
  'name': 'required',
}

new Validator(data, nested).passes() // => true
new Validator(data, flattened).passes() // => true
```

### WildCards规则

WildCards也可以被验证.

```ts
import { Validator } from '@chantouchsek/validatorjs'

const data = {
  users: [
    {
      bio: {
        age: 28,
        education: {
          primary: 'Elementary School',
          secondary: 'Secondary School',
        },
      },
      name: 'John',
    },
  ],
}
const rules = {
  'users': 'required|array',
  'users.*.bio.age': 'min:18',
  'users.*.bio.education.primary': 'string',
  'users.*.bio.education.secondary': 'string',
  'users.*.name': 'required',
}

new Validator(data, rules).passes() // => true

const invalid = new Validator({ users: [{ name: '' }] }, { 'users.*.name': 'required' })
invalid.fails() // => true
invalid.errors.first('users.0.name') // => 'The users 0 name field is required.'
```

使用父数组的规则要求至少一个项目:通配符规则 没有用于验证缺失或空数组的条目。 通配符扩展时 校验符被构建; 如果数组结构发生变化, 创建一个新实例.

### 所需有条件规则和比较

字符串-形式比较参数为字符串. 阵列形式参数保存 在比较布尔或数字时使用它们.

```ts
import { Validator } from '@chantouchsek/validatorjs'

const input = {
  account: { kind: 'business' },
  company: '',
  password: 'secret123',
  password_confirmation: 'secret123',
  email: 'ada@example.com',
  emailAgain: 'ada@example.com',
  backupEmail: 'other@example.com',
}
const rules = {
  company: 'required_if:account.kind,business',
  password: 'required|confirmed',
  emailAgain: 'required|same:email',
  backupEmail: 'required|different:email',
}
const validation = new Validator(input, rules)
validation.fails() // => true
validation.errors.has('company') // => true
validation.errorCount // => 1

new Validator({ enabled: false }, { reason: [{ required_if: ['enabled', false] }] }).passes() // => false
new Validator({ status: 'draft' }, { title: 'required_unless:status,draft' }).passes() // => true
new Validator({ email: 'ada@example.com' }, { name: 'required_with:email' }).passes() // => false
new Validator({ email: 'ada@example.com' }, { name: 'required_without:email' }).passes() // => true
new Validator({ first: 'Ada', last: 'Lovelace' }, { name: 'required_with_all:first,last' }).passes() // => false
new Validator({ first: 'Ada' }, { name: 'required_without_all:first,last' }).passes() // => true

const users = { users: [{ needsPhone: true, phone: '' }, { needsPhone: false }] }
const userRules = { 'users.*.phone': [{ required_if: ['users.*.needsPhone', true] }] }
const perUser = new Validator(users, userRules)
perUser.fails() // => true
Object.keys(perUser.errors.all()) // => ['users.0.phone']
```

`same` 财务报告和审定财务报表 `different` 使用严格的平等。 当前限制:比较路径 通过数组不能正确解决这两个规则,以及 `confirmed` 寻找一个顶级确认域。 有或无有条件规则的使用 真理,所以零和虚实的计算为缺席. 虽然他们的规则名称如下 文档多字段, `required_with` 财务报告和审定财务报表 `required_without` 目前解决 只有一个路径; 在列表处理固定之前使用单一的依赖性 .

### 现行规则

验证规则没有隐含的"要求". 如果一个字段是 _未定义_ 或空弦会过去 审定。 如果您想要对未定义或“ ” 的验证失败, 请使用 _所需经费_ 规则.

#### 已接受

被验证的字段必须是"是","在","1"或"真实". 这对验证"服务条款"的接受很有用.

#### 日期之后

被验证的字段必须在命名的顶级输入字段的日期后.

#### 等:日期之后

被验证的字段必须在命名的顶级输入字段之后或等同日期.

#### 阿尔法

正在验证的字段必须是完全字母化的字符.

#### 阿尔法达什

被验证的字段可能有字母数字字符,以及破折号和下划线.

#### α num

被验证的字段必须是完全字母化的字符.

#### 数组

正在验证的字段必须是数组 .

#### 日期:

被验证的字段必须在命名的顶级输入字段的日期之前.

#### 前为平:日期

被验证的字段必须在命名的顶级输入字段之前或等同日期.

#### 在: min, 最大值之间

正在验证的字段必须在给定分和最大分之间有大小 。 字符串、数字和数组在 和大小规则一样时尚.

#### 布尔

正在验证的字段必须是窗体的布尔值 `true`, (中文(简体) ), `false`, (中文(简体) ), `0`, (中文(简体) ), `1`, (中文(简体) ), `'true'`, (中文(简体) ), `'false'`, (中文(简体) ), `'0'` , (中文(简体) ), `'1'`, (中文(简体) ),

#### 确认

正在验证的字段必须有相匹配的 foo 确认域 。 例如,如果验证中的字段是 密码,输入中必须包含匹配的密码 确认字段.

#### 日期

正在验证的字段必须是Javascript中可接受的有效日期格式 `Date` 对象.

#### 数字:值

被验证的字段必须是数字并必须有准确的值长度.

#### 数字 在: min, max之间

目前的执行情况检查,数字值介于分钟和最大之间; 它不检查数字计数, 尽管规则的名称和错误消息.

#### 不同属性

给定的字段必须与被验证的字段不同.

#### 电子邮件

验证中的字段必须被格式化为电子邮件地址.

#### 六进制

正在验证的字段应该是十六进制格式. 与其他规则结合有用 `hex|size:6` 页:1 六分色码验证.

#### 在: foo, bar, 中, 中, 中.

验证中的字段必须包含在给定的数值列表中. 字段可以是数组或字符串.

#### 整数

正在验证的字段必须具有整数值 .

#### 最大值:值

验证属性不大于给定大小

_注:最大检查包含在内._

#### 例1 - 最大验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const rules = {
  phone: 'required|digits:11|max:11',
}
const input = {
  phone: '01234567890',
}
new Validator(input, rules).passes() // => true
```

#### 例2 - 最大验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const rules = {
  phone: 'integer|max:16',
}
const input = {
  phone: '18',
}
new Validator(input, rules).passes() // => false
```

#### 分:值

验证属性至少是一个给定大小 .

_注:最低限度检查是包容性的._

#### 例1 - 最小验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const rules = {
  phone: 'required|digits:11|min:11',
}
const input = {
  phone: '01234567890',
}
new Validator(input, rules).passes() // => true
```

#### 例2 - 最小验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const rules = {
  phone: 'integer|min:11',
}
const input = {
  phone: '18',
}
new Validator(input, rules).passes() // => true
```

#### 不是在: foo, bar, , , , ,...

验证中的字段不得包含在给定的数值列表中.

#### 数字

验证属性为数值。 一个数字的字符串表示会通过.

```ts
import { Validator } from '@chantouchsek/validatorjs'

const rules = {
  amount: 'numeric|digits:5',
}
new Validator({ amount: '12345' }, rules).passes() // => true
```

#### 当前

正在验证的字段必须具有除 `undefined`,但可以是空的.

#### 所需经费

拒绝 `null` 财务报告和审定财务报表 `undefined`,然后检查字符串表示式包含 至少有一个非空白字符。 0和假通;空数组失败.

#### 需要 if: aother field, 值

如果另一个字段严格等于所提供的值,则正在验证的字段必须是非空的.

#### 需要( u),除非:另一个字段,值

正在验证的字段必须是非空的,除非其他字段严格等于所提供的值.

#### 需要 with: foo, bar,...

正在验证的字段必须存在,而不能仅在其他指定字段中存在时才为空.

#### 需要 with all:foo, bar,...

正在验证的字段必须存在,而不能只在所有其他指定字段都存在的情况下才为空.

#### 需要 没有: foo, bar,...

正在验证的字段必须存在,而不能仅在其他指定字段不存在时才为空.

#### 需要 无 all: foo, bar,...

正在验证的字段必须存在,而不能只在所有其他指定字段不存在时才为空.

#### 有时

在某些情况下,您可能只希望对正在验证的数据中存在的字段进行验证检查。 为了迅速完成这项工作,在规则列表中加入有时的规则:

```ts
import { Validator } from '@chantouchsek/validatorjs'

const rules = {
  email: 'sometimes|required|email',
}
new Validator({}, rules).passes() // => true
new Validator({ email: '' }, rules).passes() // => false
```

在上述例子中,电子邮件字段只有在输入中存在时才会被验证.

#### 相同:属性

给定的字段必须匹配被验证的字段.

#### 大小:值

正在验证的字段必须有匹配给定值的大小 。 对于字符串数据,数值对应数字 字符的输入。 对于数值数据,值对应给定的整数值.

#### 字符串

正在验证的字段必须是字符串 .

#### url 密码

验证属性是否具有有效的 URL 格式

#### regex: 扩展

正在验证的字段必须匹配给定正则表达式 .

**说明**: 当使用 `regex` 模式,也许有必要在一个阵列中指定规则,而不是使用管 分隔符,特别是正则表达式包含管字符时. 你用过的每把后斜刀 你们的regex图案 你们必须用另一个后向斜线 来逃避对方.

#### 例3 - Regex 验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validation = new Validator(
  {
    name: 'Doe',
    salary: '10,000.00',
    yearOfBirth: '1980',
  },
  {
    name: 'required|size:3',
    salary: ['required', 'regex:/^(?!0\\.00)\\d{1,3}(,\\d{3})*(\\.\\d\\d)?$/'],
    yearOfBirth: ['required', 'regex:/^(19|20)[\\d]{2,2}$/'],
  },
)

validation.fails() // => false
validation.passes() // => true
```

#### 例4 - 类型检查验证

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validation = new Validator(
  {
    age: 30,
    name: '',
  },
  {
    age: ['required', { in: [29, 30] }],
    name: [{ required_if: ['age', 30] }],
  },
)

validation.fails() // => true
validation.passes() // => false
```

### 可选电话验证

电话验证是一种选入适配器. 明确安装其可选端点 :

```sh
pnpm add @chantouchsek/validatorjs libphonenumber-js
# Or: npm install @chantouchsek/validatorjs libphonenumber-js
# Or: yarn add @chantouchsek/validatorjs libphonenumber-js
```

导入核心软件包时不装入电话解析器或元数据 。 分开 `/phone` 输入负载 `libphonenumber-js/max` (完整的元数据),但没有登记 直到你打电话 `registerPhoneRule(Validator)`。只使用核心的用户不需要对等器; 导入 `/phone` 不产生模块解析错误。 无害环境管理和共同JS 支持进口,同时对两个条目进行TypeScript声明.

```ts
import { Validator } from '@chantouchsek/validatorjs'
import { registerPhoneRule } from '@chantouchsek/validatorjs/phone'

registerPhoneRule(Validator)

const international = new Validator({ contact: '+855 12 345 678' }, { contact: 'required|phone' })
international.passes() // => true

const national = new Validator({ contact: '012 345 678' }, { contact: 'phone:KH' })
national.passes() // => true

const missingCountry = new Validator({ contact: '012 345 678' }, { contact: 'phone' })
missingCountry.fails() // => true

const foreignCountry = new Validator({ contact: '+1 213 373 4253' }, { contact: 'phone:KH' })
foreignCountry.fails() // => true
```

`phone` 需要从 `+`。 。 。 . `phone:KH` 接受一个 国家编号或国际编号:柬埔寨。 其他大写国家 由 libphone number-js 支持的代码以同样的方式工作(`US`, (中文(简体) ), `CA`, (中文(简体) ), `GB`, (中文(简体) ), `FR`, (中文(简体) ), ,包括其支持的区域代码)。 解析的国家必须匹配, 包括共享呼叫码的国家。 国别拨号前缀 遵循解析器的国家规则. `UK`,小写代码,不支持代码,为空 `phone:`,国家清单,非字符串国家参数在评价时失败. 没有登记或格式化的选择;只使用一条规则或一个国家.

当整个输入解析为 有效号码。 绕行道,扩展道(`ext.`, (中文(简体) ), `x`),以及 `tel:` URIs为 拒绝。 只接受原始字符串; 数字输入会丢失正 0 绝不能使用。 编号计划的有效性 **没有** 证明任务, 所有权、可达到性或短信能力。 保持可选对等电流,因为 它的元数据决定了有效性.

空值遵循现有的非隐规则行为 :

```ts
import { Validator } from '@chantouchsek/validatorjs'
import { registerPhoneRule } from '@chantouchsek/validatorjs/phone'

registerPhoneRule(Validator)
new Validator({}, { contact: 'phone' }).passes() // => true
new Validator({ contact: null }, { contact: 'phone' }).passes() // => true
new Validator({ contact: '' }, { contact: 'required|phone' }).fails() // => true
new Validator({}, { contact: 'sometimes|required|phone' }).passes() // => true
new Validator({ contact: '' }, { contact: 'sometimes|required|phone' }).fails() // => true
new Validator({ contact: [] }, { contact: 'phone' }).fails() // => true
```

缺少、 未定义、 无效、 空和 仅空白值跳过 `phone`; 添加 `required` 需要一个值。 对阵列进行评估并否决. `present`, (中文(简体) ), `nullable`,而有条件的规则保留其现有的语义. 跳过可选值的无效的国家选项不是飞行前错误 .

嵌入字段、通配符规则、信件和属性名称使用现有的 API :

```ts
import { Validator } from '@chantouchsek/validatorjs'
import { registerPhoneRule } from '@chantouchsek/validatorjs/phone'

registerPhoneRule(Validator)
const input = { contacts: [{ number: 'bad' }, { number: '+855 12 345 678' }] }
const validation = new Validator(input, { 'contacts.*.number': 'required|phone:KH' }, {
  customMessages: { 'phone.contacts.*.number': 'Enter a valid phone number for :attribute.' },
  customAttributes: { 'contacts.*.number': 'contact number' },
})
validation.fails() // => true
validation.errors.first('contacts.0.number') // => 'Enter a valid phone number for contact number.'

const valid = new Validator({ contact: '  +855 12 345 678  ' }, { contact: 'phone' })
valid.validated() // => { contact: '  +855 12 345 678  ' }
```

验证从不格式化或变异输入; `validated()` 保留所提供的 绳子。 登记可以重复,并明确取代现有的 同步 `phone` 规则。 为适配器保留规定名称.

电话留言使用当地人 `phone` 模板当存在时,然后其已存在的 常规 `def` 倒计时(英语: `The contact attribute has errors.`) (中文(简体) ). 实例 自定义消息为正常优先。 提供本地化电话文本 :

```ts
import { Validator } from '@chantouchsek/validatorjs'
import { registerPhoneRule } from '@chantouchsek/validatorjs/phone'

const previousLocale = Validator.getDefaultLang()
const original = Validator.getMessages('fr')
Validator.setMessages('fr', { ...original, phone: 'Le numéro :attribute est invalide.' })
Validator.useLang('fr')
registerPhoneRule(Validator) // Preserves this translation and the default locale.

const validation = new Validator({ contact: 'bad' }, { contact: 'phone' }, { locale: 'fr' })
validation.fails() // => true
validation.errors.first('contact') // => 'Le numéro contact est invalide.'

Validator.setMessages('fr', original)
Validator.useLang(previousLocale)
```

可选适配器只对导入的应用程序添加 parser/ full-metadata 成本 `/phone`;对等点仍然属于此软件包构建的外部. 现有核心 出口、文件验证行为和消费者节点要求保持不变.

### 注册自定义验证规则

使用 `Validator.register(name, callbackFn, errorMessage?)`。 。 。 .

**名称** - 规则的名称.

**回调Fn** {功能} - 返回布尔来表示一个成功或失败的验证 .

**错误** {String} - 一个可以指定自定义错误消息的可选字符串. _: 属性_ 内部 错误信息将替换为属性名称 .

```ts
import { Validator } from '@chantouchsek/validatorjs'

Validator.register(
  'telephone',
  (value: unknown, _requirement: unknown, _attribute: string): boolean =>
    typeof value === 'string' && /^\d{3}-\d{3}-\d{4}$/.test(value),
  'The :attribute is not in the format XXX-XXX-XXXX.',
)

const validation = new Validator({ phone: '123-456-7890' }, { phone: 'required|telephone' })
validation.passes() // => true
const invalid = new Validator({ phone: '123' }, { phone: 'required|telephone' })
invalid.fails() // => true
invalid.errors.first('phone') // => 'The phone is not in the format XXX-XXX-XXXX.'
```

回电收到 `(value, requirement, attribute)`。没有参数的规则 接收 `undefined` 作为它的要求。 普通自定义规则跳过缺失/空 值;将其与 `required`,或使用 `registerImplicit` 习惯规则 它必须运行在空输入上。 所有验证人都共享登记.

### 同步验证

登记一条同步规则,该规则接受回复召回作为第四个规则 参数。 召回一次,包括失败;返回 规则中的承诺不会自动解决验证问题.

```ts
import { Validator } from '@chantouchsek/validatorjs'

type Respond = (passed?: boolean, message?: string) => void
Validator.registerAsync(
  'username_available',
  (username: string, _requirement: unknown, _attribute: string, respond: Respond): void => {
    setTimeout(() => {
      if (username === 'taken') respond(false, 'Username has already been taken.')
      else respond()
    }, 0)
  },
  'The :attribute is unavailable.',
)

const validator = new Validator(
  {
    username: 'taken',
  },
  {
    username: 'required|min:3|username_available',
  },
)

const passed = await validator.passesAsync()
passed // => false
validator.errors.first('username') // => 'Username has already been taken.'
```

此示例使用顶级 `await` 在ES模块中运行;也可以在其中运行 `async` 函数. `passesAsync()` 决定 `true` 或者说 `false` 审定完成后; 读取 `errors` 财务报告和审定财务报表 `errorCount` 之后的个案。 时抛出错误 援引验证,例如未知规则,拒绝承诺,而不是 解决 `false`。随后在应用程序管理的计时器中推出的例外情况不是 自动抓取,而自定义的async规则仍然必须调用他们的回回回复.

它还支持同步规则而不用单独的包装:

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validator = new Validator({ email: 'ada@example.com' }, { email: 'required|email' })
const passed: boolean = await validator.passesAsync()
passed // => true
validator.errors.all() // => {}
```

回调 API 仍然可用: 当 ASync 规则存在时, `passes(callback)` 财务报告和审定财务报表 `fails(callback)` 需要回话. `checkAsync(onPass, onFail)` 处理两个 成果和回报 `void`。完成一次验证,然后启动另一次验证 同样的情况。 一项从未回应的习惯规则仍然有待验证; `passesAsync()` 不添加超时或采用从习惯规则中返回的许诺.

### 与有效输入合作

使用 `validated()` 方法只检索经验证的数据,并过滤所提供的规则中没有的属性.

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validation = new Validator(
  {
    age: 28,
    email: 'johndoe@gmail.com',
    gender: 'male',
    name: 'John',
  },
  {
    age: 'min:18',
    name: 'required',
  },
)
validation.validated() // => { name: 'John', age: 28 }
```

`validated()` 当当前验证失败时,方法会出错.

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validation = new Validator(
  {
    age: 28,
    email: 'johndoe@gmail.com',
    gender: 'male',
    name: 'John',
  },
  {
    age: 'min:40',
    name: 'required',
  },
)
validation.validated() // throws: Validation failed!
```

`validated()` 也进行同步验证。 它的第一个回电收到 过滤后的数据作为其第一个参数;第二个回调处理失败.

```ts
import { Validator } from '@chantouchsek/validatorjs'

type Respond = (passed?: boolean, message?: string) => void
Validator.registerAsync('allowed_name', (value: string, _requirement: unknown, _attribute: string, respond: Respond): void => {
  setTimeout(() => respond(value !== 'blocked'), 0)
}, 'The :attribute is blocked.')

const validation = new Validator(
  {
    age: 28,
    email: 'johndoe@gmail.com',
    gender: 'male',
    name: 'John',
  },
  {
    age: 'min:18',
    name: 'required|allowed_name',
  },
)
const data = await new Promise<Record<string, unknown>>((resolve, reject) => {
  validation.validated(
    (validated: Record<string, unknown>) => resolve(validated),
    () => reject(new Error('Validation failed')),
  )
})
data // => { name: 'John', age: 28 }
```

对于嵌入式数据,将规则放入您想要返回的叶地:

```ts
import { Validator } from '@chantouchsek/validatorjs'

const input = {
  user: { name: 'Ada', secret: 'hidden' },
  items: [{ sku: 'A1', price: 10, internal: 'hidden' }],
  extra: 'hidden',
}
const rules = { 'user.name': 'required', 'items.*.sku': 'required', 'items.*.price': 'numeric' }
new Validator(input, rules).validated() // => { user: { name: 'Ada' }, items: [{ sku: 'A1', price: 10 }] }
```

`validated()` 再次检查输入并返回一个 JSON 克隆投影, 不 类型强制或推断输出类型。 使用 JSON 兼容输入 。 目前的限制 : 校验只有数组母程序可以删除其元素, 未规则的对象可以保留 作为空容器,以及 `null` 由于无法预测全部输入。 使用叶 可预测的过滤规则;这种方法不是一个通用的消毒器.

### 错误消息

此构造器会自动生成错误消息, 用于验证规则失败 .

如果出现错误, 验证器实例将拥有其 **错误** 带有错误消息的属性对象 对于所有失败的属性。 方法与属性 **错误** 属性对象为:

#### 第一(属性)

返回属性的第一个错误消息,或 `undefined` 不存在时

#### .get(属性)

返回属性错误消息数组,如果没有错误,则返回空数组

#### 全部( )

返回包含所有失败属性的错误消息的对象

#### .has( 属性)

如果属性存在错误消息, 返回为真, 否则为假

#### 错误

关于验证器实例的失败规则数量( E)`validation.errorCount`, (中文(简体) ), 不是财产在 `validation.errors`。 。 。 .

```ts
import { Validator } from '@chantouchsek/validatorjs'

const input = { email: 'invalid' }
const rules = { email: 'required|email' }
const validation = new Validator(input, rules)
validation.fails()
validation.errors.first('email') // => 'The email format is invalid.'
validation.errors.get('email') // => ['The email format is invalid.']
```

### 自定义错误消息

第三个参数中的 Pass 覆盖 `customMessages` 属性。 使用规则 所有字段的名称,或 `rule.attribute` 对于特定的领域.

```ts
import { Validator } from '@chantouchsek/validatorjs'

const input = {
  name: '',
}

const rules = {
  name: 'required',
}

const validation = new Validator(input, rules, {
  customMessages: { required: 'You forgot to give a :attribute' },
})
validation.passes() // => false
validation.errors.first('name') // => 'You forgot to give a name'
```

一些验证器有字符串和数字版本. 你也可以改变它们.

```ts
import { Validator } from '@chantouchsek/validatorjs'

const input = {
  username: 'myusernameistoolong',
}

const rules = {
  username: 'max:16',
}

const validation = new Validator(input, rules, {
  customMessages: {
    max: {
      string: 'The :attribute is too long. Max length is :max.',
    },
  },
})
validation.passes() // => false
validation.errors.first('username') // => 'The username is too long. Max length is 16.'
```

您甚至可以在每个属性的基础上提供错误消息 ! 只要设置信件的密钥“ 验证器. 属性 ”

```ts
import { Validator } from '@chantouchsek/validatorjs'

const input = { email: '', name: '' }
const rules = { email: 'required', name: 'required' }

const validation = new Validator(input, rules, {
  customMessages: { 'required.email': 'Without an :attribute we can\'t reach you!' },
})

validation.passes() // => false
validation.errors.first('name') // => 'The name field is required.'
validation.errors.first('email') // => 'Without an email we can\'t reach you!'
```

### 自定义属性名称

#### 使用自定义属性名称的配置

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validator = new Validator(
  { form: { name: null } },
  { form: { age: 'required', name: 'required' } },
  {
    customAttributes: { form: { name: 'Username' } },
    customMessages: {
      required: 'The :attribute must be filled.',
    },
  },
)
if (validator.fails())
  validator.errors.first('form.name') // => 'The Username must be filled.'
```

要在错误消息中显示自定义的“ 友好” 属性名称, 请使用 `.setAttributeNames()`

```ts
import { Validator } from '@chantouchsek/validatorjs'

const validator = new Validator({ name: '' }, { name: 'required' })
validator.setAttributeNames({ name: 'custom_name' })
if (validator.fails())
  validator.errors.first('name') // => 'The custom_name field is required.'
```

或者,您可以使用 `attributes` 属性.

您也可以配置自定义属性 formatter :

```ts
import { Validator } from '@chantouchsek/validatorjs'

// Configure global formatter.
Validator.setAttributeFormatter((attribute: string) => {
  return attribute.replace(/_/g, ' ')
})

// Or configure formatter for particular instance.
const validator = new Validator({ first_name: '' }, { first_name: 'required' })
validator.setAttributeFormatter((attribute: string) => {
  return attribute.replace(/_/g, ' ')
})
if (validator.fails())
  validator.errors.first('first_name') // => 'The first name field is required.'
```

注意:默认情况下,所有 字符将被替换为空格.

### 语言支持

本地人被捆绑在公共软件包条目中. 使用节点或节点中命名的导入 浏览器捆绑器; 没有单独的 `dist/lang/*.js` 需要导入。 英语是 初始默认 . `LangTypes` 列出所支持的语言代码.

```ts
import type { ValidatorOptions } from '@chantouchsek/validatorjs'
import { Validator } from '@chantouchsek/validatorjs'

const previousLocale = Validator.getDefaultLang()
const options: ValidatorOptions = { locale: 'fr', customAttributes: { name: 'Nom' } }
const validation = new Validator({ name: '' }, { name: 'required' }, options)
validation.fails() // => true
validation.errors.first('name') // => 'Le champ Nom est requis.'
Validator.useLang(previousLocale)
```

目前,正在建造一个验证器,其中 `locale` 也改变全局默认值 适用于后来的验证人和习惯规则登记。 设置或恢复默认值 在共享应用程序中明确。 使用支持的地块; 未知代码没有 自动后退。 要设置后续实例的默认值 :

```ts
import { Validator } from '@chantouchsek/validatorjs'

const previousLocale = Validator.getDefaultLang()
Validator.useLang('km')
Validator.getDefaultLang() // => 'km'
const validation = new Validator({ name: '' }, { name: 'required' })
validation.fails() // => true
validation.errors.first('name') // => 'ឈ្មោះ ត្រូវតែបញ្ចូលជាដាច់ខាត។'
Validator.useLang(previousLocale)
```

`getMessages` 返回共享语言词典。 在压倒一切的消息之前复制它 与 `setMessages`; 保存其他模板,这样不相关的规则仍然可以渲染:

```ts
import { Validator } from '@chantouchsek/validatorjs'

const original = Validator.getMessages('en')
Validator.setMessages('en', { ...original, required: 'Whoops, :attribute is required.' })
const validation = new Validator({}, { name: 'required' }, { locale: 'en' })
validation.fails() // => true
validation.errors.first('name') // => 'Whoops, name is required.'
Validator.setMessages('en', original)
```

如果你没有看到支持 你的语言,请添加一个 `src/lang`来啊!

### 发展

使用pnpm 10.26.0和Node.js 22.22.2+, 24.15.0+,或26+来进行开发. 这些要求来自开发工具;已出版的成套文件仍然 支持节点.js `^12.20.0 || >=14.13.0`。 。 。 .

```sh
pnpm install --frozen-lockfile
pnpm test:cov
pnpm typecheck
pnpm lint
pnpm build
pnpm test:package
```

包检查将本地沥青球安装到临时项目中,核实无害环境管理 和普通JS行为,并检查两种声明格式。 检查一个老人 消费者运行时间,将其节点可执行文件传递给 `pnpm test:package /path/to/node`· ; 检查本身必须在开发节点版本上运行.

### 许可证

版权所有:2020-Present Chantouch Sek

根据麻省理工学院许可证获释

### 贷项

校验器 Js 由 Chantouch Sek 重写

电子邮件 : [shantouchsek.cs83@gmail.com 页面存档备份,存于互联网档案馆](mailto:chantouchsek.cs93@gmail.com)

微博 [@ DevidCs83 (英语)](https://twitter.com/DevidCs83)

网站: [钱通克](https://chantouch.me/)

## 常见问题

### @chantouchsek/validatorjs 是什么？

校验器\.js库使得JavaScript中的数据验证在浏览器和Node\.js中都非常容易\.

### 如何安装 @chantouchsek/validatorjs？

在项目目录运行 npm install @chantouchsek/validatorjs，或使用 pnpm add / yarn add / bun add。

### @chantouchsek/validatorjs 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @chantouchsek/validatorjs 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @chantouchsek/validatorjs 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^12\.20\.0 \|\| \>=14\.13\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @chantouchsek/validatorjs 可以商用吗？

@chantouchsek/validatorjs 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @chantouchsek/validatorjs 的下载量有多少？

根据 npm 官方下载统计，@chantouchsek/validatorjs 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,891 次，日均约 96 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @chantouchsek/validatorjs 还在维护吗？

最新版本 2\.3\.0 发布于 2026/10/17（23 天前）；至今共发布 57 个版本，其中过去 12 个月发布了 5 个；首次发布于 2020/07/23。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

