.runkit_example.js 496 B

1234567891011121314151617181920212223
  1. const Ajv = require("ajv")
  2. const ajv = new Ajv({allErrors: true})
  3. const schema = {
  4. type: "object",
  5. properties: {
  6. foo: {type: "string"},
  7. bar: {type: "number", maximum: 3},
  8. },
  9. required: ["foo", "bar"],
  10. additionalProperties: false,
  11. }
  12. const validate = ajv.compile(schema)
  13. test({foo: "abc", bar: 2})
  14. test({foo: 2, bar: 4})
  15. function test(data) {
  16. const valid = validate(data)
  17. if (valid) console.log("Valid!")
  18. else console.log("Invalid: " + ajv.errorsText(validate.errors))
  19. }