美文网首页
json_schema + ajv

json_schema + ajv

作者: wyc0859 | 来源:发表于2021-08-31 16:48 被阅读0次

    json_schema: 用于是描述你的JSON数据和规范格式
    网站: http://json-schema.org/
    不需要安装

    ajv: 是JSON Schema的验证工具
    网站: https://ajv.js.org/
    安装:

    yarn add ajv -S
    yarn add ajv-errors -S
    yarn add ajv-i18n -S
    yarn add ajv-formats -S
    

    如果上面代码报错,请执行下2句:

    npm config set registry https://registry.npm.taobao.org
    npm config set disturl https://npm.taobao.org/dist
    

    简单示例代码

    const Ajv = require('ajv')
    const localize = require('ajv-i18n')  //中文
    
    //pets会警告,因为它定义了不受约束的元组。
    //要定义一个正好包含 2 个元素的元组, 需minItems:2,additionalItems: false
    const schema = {
      type: 'object',
      properties: {
        name: {
          type: 'string'
        },
        age: {
          type: 'number',
        },
        pets: {
          type: 'array',
          items: [
            {
              type: 'string',
            },
            {
              type: 'number',
            }
          ],      
          // minItems:2,      
          // additionalItems: false
        }
      },
      required: ['name', 'age']
    }
    
    const ajv = new Ajv() 
    const validate = ajv.compile(schema)
    const valid = validate({
      name: 'haha',
      age: "18a",
      pets: ['mimi', 12]
    })
    if (!valid) { 
      localize.zh(validate.errors)  //将报错信息转为中文
      console.log(validate.errors)
    }
    

    format

    内置format和自定义format

    const Ajv = require("ajv")
    const localize = require('ajv-i18n') 
    const addFormats = require("ajv-formats")  //**引入**
    const ajv = new Ajv() 
    addFormats(ajv)
    
    const schema = {
      type: 'object',
      properties: {
        name: {
          type: 'string',
          format:'email'  //***内置****
        },
        age: {  
          type: "number",
          format:'qy'  //****自定义***
        }
      },
      required: ['name']
    }
     
    //自定义 
    ajv.addFormat("qy", {
      type: "number",
      validate: (x)=>{
        return x>5?true:false
      }
    })
    
    const validate = ajv.compile(schema)
    const valid = validate({
      name: 'haha@qq.com',
      age:1
    })
    if (!valid) { 
      localize.zh(validate.errors)  //将报错信息转为中文
      console.log(validate.errors)
    }
    

    关键字

    关键字是3种类型
    1、 "validate" function
    2、 "compile" function
    3、 "macro" function

    const Ajv = require("ajv")
    const localize = require('ajv-i18n')  //中文 
    const ajv = new Ajv()  
    
    const schema = {
      type: 'object',
      properties: {
        name: {
          type: 'string',
          test3: false
        } 
      },
      required: ['name']
    }
     
    // validate类型  
    ajv.addKeyword('test1', {
      validate(schema, data) {
        console.log("普通:",schema, data)
        if (schema === true) return true
        else return data.length === 6
      },
    })
    
    // compile类型
    ajv.addKeyword('test2', {
      compile(sch, parentSchema) {
        console.log("compile:",sch, parentSchema) 
        return (x) => {
          if(x.length===6){
            return true
          }else{
            return false
          }
        }
      }
    })
    // macro型  
    ajv.addKeyword('test3', {
      macro() {
        return {
          minLength: 10,
        }
      },
    })
    const validate = ajv.compile(schema)
    const valid = validate({
      name: 'ha12ha'
    })
    if (!valid) { 
      localize.zh(validate.errors)  //将报错信息转为中文
      console.log(validate.errors)
    }
    

    自定义错误

    const Ajv = require("ajv").default
    const localize = require('ajv-i18n')  //中文 
    const ajv = new Ajv({allErrors: true})
    require("ajv-errors")(ajv /*, {singleError: true} */)
    
    const schema = {
      type: "object",
      properties: {
        name: {
          type: 'string',
          minLength:10,
          errorMessage: {  //单个属性验证的错误提示
            type:"name必须是string",
            minLength:"name长度不能小于10"
          }
        },
        age: {
          type: 'number'
        },
      },
      required: ['name'],
      //errorMessage: "name或age错误", //这里是统一设置错误,无论是name还是age错,都会报这句
    }
    
    const validate = ajv.compile(schema)
    const valid = validate({
      name: "abc1221",
      age: 3
    })
    if (!valid) { 
      console.log(validate.errors)
      console.log("*****************")
      localize.zh(validate.errors)  //将报错信息转为中文
    }else{
      console.log("通过")
    }
    

    相关文章

      网友评论

          本文标题:json_schema + ajv

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