joi

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Joi

Joi

Quick Start

快速开始

const Joi = require('@hapi/joi');
const schema = Joi.object({
    name: Joi.string().min(1).max(100).required(),
    age: Joi.number().integer().min(0),
    email: Joi.string().email()
});

const { error, value } = schema.validate(input);
const Joi = require('@hapi/joi');
const schema = Joi.object({
    name: Joi.string().min(1).max(100).required(),
    age: Joi.number().integer().min(0),
    email: Joi.string().email()
});

const { error, value } = schema.validate(input);

Critical Rules

核心规则

  1. Schemas are immutable - Every method returns a new schema instance; never mutate
  2. Validate at boundaries - Use
    validate()
    or
    attempt()
    at input boundaries; see validation
  3. Types extend base - All types inherit from
    any()
    ; see types overview
  4. Refs for cross-field - Use
    Joi.ref()
    for dynamic values across fields; see references
  5. Extend for custom types - Use
    Joi.extend()
    to create custom types; see extensions
  1. Schema不可变 - 每个方法都会返回新的schema实例;切勿直接修改原实例
  2. 在边界处验证 - 在输入边界使用
    validate()
    attempt()
    ;详见验证
  3. 类型继承基础类型 - 所有类型都继承自
    any()
    ;详见类型概览
  4. 跨字段引用 - 使用
    Joi.ref()
    实现字段间的动态值引用;详见引用
  5. 扩展自定义类型 - 使用
    Joi.extend()
    创建自定义类型;详见扩展

Workflow

工作流程

  1. Choose a type - types overview for all built-in types
  2. Add constraints - Chain rules like
    .min()
    ,
    .max()
    ,
    .pattern()
    ,
    .valid()
  3. Compose schemas - Nest
    Joi.object()
    ,
    Joi.array()
    ,
    Joi.alternatives()
  4. Add conditionals - Use
    .when()
    for dynamic schemas; see conditionals
  5. Customize errors - Override messages via
    .messages()
    or
    .error()
    ; see errors
  1. 选择类型 - 查看类型概览了解所有内置类型
  2. 添加约束 - 链式调用
    .min()
    .max()
    .pattern()
    .valid()
    等规则
  3. 组合Schema - 嵌套使用
    Joi.object()
    Joi.array()
    Joi.alternatives()
  4. 添加条件判断 - 使用
    .when()
    实现动态Schema;详见条件判断
  5. 自定义错误信息 - 通过
    .messages()
    .error()
    覆盖默认提示;详见错误处理

Key Patterns

核心模式

TopicReference
All built-in typestypes
Validation & optionsvalidation
References & templatesreferences
Conditional schemasconditionals
Error handlingerrors
Custom extensionsextensions
Metadata & introspectionmetadata
Common methods (any)any
Testing patternstesting
主题参考文档
所有内置类型types
验证与选项validation
引用与模板references
条件Schemaconditionals
错误处理errors
自定义扩展extensions
元数据与自省metadata
通用方法(any类型)any
测试模式testing