美文网首页
【nodeJs】工具模块 joi

【nodeJs】工具模块 joi

作者: 前端菜篮子 | 来源:发表于2021-11-09 15:35 被阅读0次

node.js 使用joi来验证数据模型

joinodejs的一个工具模块,主要用于JavaScript对象的校验。它是一种简单易用的javacript对象约束描述语言,可以轻松解决nodejs开发中的各种参数的校验。

// 导入joi模块 
const joi = require('joi')

// 定义验证规则
const schema = joi.object({
    // username必须是字符串类型、最小长度是2、最大长度是6、必填项、自定义验证失败错误信息
    username: joi.string().min(2).max(6).required().error(new Error('用户名格式不正确')),
    // email必须是字符串类型、必须符合邮箱格式、必填项、自定义验证失败错误信息
    email: joi.string().email().required().error(new Error('邮箱格式不正确')),
    // pwd必须是字符串类型、必须符合指定的正则规则、自定义验证失败错误信息
    pwd: joi.string().regex(/^[a-zA-Z0-9]+$/).error(new Error('密码格式不正确')),
    // sex必须是数字类型、值是0或1、必填项、自定义验证失败错误信息
    sex: joi.number().valid(0, 1).required().error(new Error('性别格式不正确')),
   // 可以根据sex的值来定义name2的类型属性
    name2: joi.when('sex',
        {
            is: 1,
            then: joi.string().required().error(new Error('name2格式不正确'))
        }),

    name3: joi.string().max(2).allow('').error(new Error('name3格式不正确')),
   // 针对数组的操作 
    orderItems: joi.array().items(
        joi.object().keys({
            thirdOrderItemId: joi.string().required().error(new Error('订单明细ID不能为空')),
            productName: joi.string().required().error(new Error('商品名称不能为空'))

        })
    )
});

let body = {
    username: "adm",
    email: 'admin@qq.com',
    pwd: 'abc123',
    sex: 1,
    phone: '13',
    name2: "1",
    name3: "",
    orderItems: '[{\"thirdOrderItemId\": \"123\",\"productName\": \"151515\"}]'
};

body.orderItems = JSON.parse(body.orderItems)  // 针对数组操作必须是json对象,如果是json字符串需要自己解析一次。

async function run() {
    try {
        /*验证*/
        await schema.validateAsync(body, { allowUnknown: true, abortEarly: true }); 
        console.log('验证成功');
    } catch (e) {
        console.log(e.message);
    }
}

run();

另外还有一些基本的操作粘在下面以作参考

// 3 - 30 个 数字、字符
username: Joi.string().alphanum().min(3).max(30).required(),

// 3 - 30 位 字母数字组合密码
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),

// string || number 都可以通过
access_token: [Joi.string(), Joi.number()],

// 生日限制
birthyear: Joi.number().integer().min(1900).max(2018),

// email 限制
email: Joi.string().email(),

// URI限制
website: Joi.string().uri({ scheme: [ 'git', /git+https?/ ] }),

// ==== 允许为空/ 否认不允许为空 ====
search: Joi.string().allow(''),

// 验证枚举值,如果不传,默认为all
type: Joi.string().valid('disabled', 'normal', 'all').default('all'),

// 开始时间 会自动格式化
startTime: Joi.date().min('1-1-1974').max('now'),

// 结束时间 必须大于开始时间,小于2100-1-1
endTime: Joi.when(Joi.ref('startTime'), { is: Joi.date().required(), then: Joi.date().max('1-1-2100') }),

// 页码 限制最小值
page: Joi.number().integer().min(1).default(1), pageSize: Joi.number().integer().default(8),
// deleteWhenLtTen: Joi.number().integer().max(10).strip(),

// 数组中包含某个字段 && 数字
arrayString: Joi.array().items(
// 数组中必须包含 name1
Joi.string().label('name1').required(),
// 数组中必须包含 数字
Joi.number().required(),
// 除掉【以上类型的以外字段】---数组中可以包含其他类型,如bool
Joi.any().strip()
),

// 数组对象, 如需其参考以上字段
arrayObject: Joi.array().items(
  Joi.object().keys({
    age: Joi.number().integer().max(200),
    sex: Joi.boolean()
  })
)

with('isA', 'AVal') //意思是,isA 和 AVal 这两字段如果填写了isA,也必须要填写AVal
with('isB', 'BVal') //道理同上
without('isA', 'isB'); //意思是 isA 和 isB 只能填写其中一个
or('isA', 'isB') //意思是 isA 和 isB 这两字段至少填写其一

值得注意的地方是:在安装的时候一定要指定版本,然后根据指定版本的文档去看详细的操作。

allowUnknown - 如果为 true,则允许对象包含被忽略的未知键。 默认为 false。

abortEarly - 当为真时,停止对第一个错误的验证,否则返回找到的所有错误。 默认为 true。

如:npm install joi@17.3.0

官方文档https://joi.dev/api/?v=17.4.2
github地址https://github.com/sideway/joi/blob/v17.3.0/API.md

相关文章

  • 【nodeJs】工具模块 joi

    转 node.js 使用joi来验证数据模型[https://www.cnblogs.com/shenghuota...

  • 初识nodejs

    初识nodejs nodejs需会工具 nvm工具实现nodejs任意版本切换 npm下载nodejs所需模块 n...

  • NodeJS 官方文档v5.3.0 学习笔记

    https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...

  • web前端开发环境搭建

    使用到的工具: NodeJs (组件管理) GIT (代码管理) browserify (模块化) Sass (...

  • nodejs-模块

    nodejs模块 一、nodejs模块分类 1.核心模块 Core Module、内置模块、原生模块 fs模块 p...

  • nodejs入门总结三:nodejs模块

    四、nodejs模块 1.常见的模块规范:CommonJS: 最初被应用在nodejs,被称为nodejs的模块规...

  • nodeJS学习笔记(1) --- 模块系统

    nodeJs模块系统 nodeJs提供一个简单的模块系统。模块是nodeJs应用程序的基本组成部分, 模块与文件一...

  • Nodejs path模块

    path(路径) path是nodejs的模块,提供了一些工具函数,用于处理文件与目录的路径使用方法 path模块...

  • nodejs03-commonjs

    CommonJs CommonJs是模块化的标准,nodejs是模块化的实现 nodejs模块 核心模块(node...

  • nodejs模块

    nodejs模块 nodejs系统自带的模块:http:协议请求模块;创建服务器:http.createServe...

网友评论

      本文标题:【nodeJs】工具模块 joi

      本文链接:https://www.haomeiwen.com/subject/adomzltx.html