joi
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJoi
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
核心规则
- Schemas are immutable - Every method returns a new schema instance; never mutate
- Validate at boundaries - Use or
validate()at input boundaries; see validationattempt() - Types extend base - All types inherit from ; see types overview
any() - Refs for cross-field - Use for dynamic values across fields; see references
Joi.ref() - Extend for custom types - Use to create custom types; see extensions
Joi.extend()
- Schema不可变 - 每个方法都会返回新的schema实例;切勿直接修改原实例
- 在边界处验证 - 在输入边界使用或
validate();详见验证attempt() - 类型继承基础类型 - 所有类型都继承自;详见类型概览
any() - 跨字段引用 - 使用实现字段间的动态值引用;详见引用
Joi.ref() - 扩展自定义类型 - 使用创建自定义类型;详见扩展
Joi.extend()
Workflow
工作流程
- Choose a type - types overview for all built-in types
- Add constraints - Chain rules like ,
.min(),.max(),.pattern().valid() - Compose schemas - Nest ,
Joi.object(),Joi.array()Joi.alternatives() - Add conditionals - Use for dynamic schemas; see conditionals
.when() - Customize errors - Override messages via or
.messages(); see errors.error()
- 选择类型 - 查看类型概览了解所有内置类型
- 添加约束 - 链式调用、
.min()、.max()、.pattern()等规则.valid() - 组合Schema - 嵌套使用、
Joi.object()、Joi.array()Joi.alternatives() - 添加条件判断 - 使用实现动态Schema;详见条件判断
.when() - 自定义错误信息 - 通过或
.messages()覆盖默认提示;详见错误处理.error()
Key Patterns
核心模式
| Topic | Reference |
|---|---|
| All built-in types | types |
| Validation & options | validation |
| References & templates | references |
| Conditional schemas | conditionals |
| Error handling | errors |
| Custom extensions | extensions |
| Metadata & introspection | metadata |
| Common methods (any) | any |
| Testing patterns | testing |
| 主题 | 参考文档 |
|---|---|
| 所有内置类型 | types |
| 验证与选项 | validation |
| 引用与模板 | references |
| 条件Schema | conditionals |
| 错误处理 | errors |
| 自定义扩展 | extensions |
| 元数据与自省 | metadata |
| 通用方法(any类型) | any |
| 测试模式 | testing |