https://github.com/ajv-validator/ajv-formats
Ajv formats类型 https://ajv.js.org/options.html#formats
formats只校验字符串和数字类型的数据,其他类型是无效的

  • string
  • number
  1. // es6 require
  2. import Ajv from "ajv"
  3. import addFormats from "ajv-formats"
  4. // Node.js require
  5. const Ajv = require("ajv")
  6. const addFormats = require("ajv-formats")
  7. const ajv = new Ajv()
  8. addFormats(ajv)

formats

image.png

ajv.addFormat 添加校验规则

https://ajv.js.org/api.html#ajv-addformat-name-string-format-format-ajv

  1. // ajv.addFormat(name: string, format: Format)
  2. import Ajv from "ajv"
  3. const ajv = new Ajv();
  4. ajv.addFormat('validateUserName', data => {
  5. console.log('data', data);
  6. return data === 'lucy'
  7. })
  8. // 使用自定义的 format
  9. const schema = {
  10. type: 'object',
  11. properties: {
  12. name: {
  13. type: 'string',
  14. format: 'validateUserName'
  15. },
  16. age: {
  17. type: 'number'
  18. },
  19. pets: {
  20. type: 'array',
  21. items: [
  22. {type: 'string'}, {type: 'number'}
  23. ]
  24. }
  25. },
  26. required: ['name', 'age']
  27. }
  28. const validate = ajv.compile(schema);
  29. const valid = validate({
  30. name: 'lucy',
  31. age: 18,
  32. })