zoukankan      html  css  js  c++  java
  • node.js 使用joi来验证数据模型

            joi是nodej的一个工具模块,主要用于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

    生活太矮!!在一条没有尽头的路上,我们低头奔跑···
  • 相关阅读:
    使用JDBCTemplate执行DQL/DML语句
    spring中JDBCTemplate的简单应用
    Druid数据库连接池工具类
    Same Tree
    Remove Duplicates from Sorted List
    Length of Last Word
    Remove Element
    Remove Duplicates from Sorted Array
    java-StringBuffer更改功能
    java-StringBuffer的删除功能
  • 原文地址:https://www.cnblogs.com/shenghuotaiai/p/joi.html
Copyright © 2011-2022 走看看