ajv

  1. const Ajv = require("ajv")
  2. const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
  3. const schema = {
  4. type: "object",
  5. properties: {
  6. foo: { type: "integer" },
  7. bar: { type: "string" }
  8. },
  9. required: ["foo"],
  10. additionalProperties: false
  11. }
  12. const validate = ajv.compile(schema)
  13. const data = {
  14. foo: "1",
  15. bar: "abc"
  16. }
  17. const valid = validate(data)
  18. if (!valid) console.log(validate.errors)
  1. // 如果错了
  2. [
  3. {
  4. instancePath: '/foo',
  5. schemaPath: '#/properties/foo/type',
  6. keyword: 'type',
  7. params: { type: 'integer' },
  8. message: 'must be integer'
  9. }
  10. ]

format

https://ajv.js.org/guide/formats.html

String formats

还可以自定义

  1. ajv.addFormat("byte", {
  2. type: "number",
  3. validate: (x) => x >= 0 && x <= 255 && x % 1 == 0,
  4. })

keyword

  1. ajv.addKeyWord("test", {
  2. validate: (schema,data) { //schema是关键字的值,data是关键字所在的key
  3. if(schema === true) return true
  4. else return schema.length === 6
  5. }
  6. })

https://ajv.js.org/packages/ajv-i18n.html

https://ajv.js.org/packages/ajv-errors.html