-
Notifications
You must be signed in to change notification settings - Fork 1
/
example-ajv.js
43 lines (38 loc) · 862 Bytes
/
example-ajv.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Define a JSON schema, which describes the structure and
* types we expect for our data.
*/
const iceCreamSchema = {
type: "object",
properties: {
flavour: { type: "string" },
price: { type: "number" },
stock: { type: "integer" },
},
required: ["flavour", "price", "stock"],
};
/**
* Define the data which we want to validate.
*/
const iceCreamData = {
flavour: "Pistachio",
price: 1.99,
stock: null,
};
/**
* Import the Ajv library and create a new Ajv instance.
*/
import Ajv from "ajv";
const ajv = new Ajv();
/**
* Validate data against our ice cream schema.
*/
const isDataValid = ajv.validate(iceCreamSchema, iceCreamData);
/**
* Output the validation results.
*/
if (isDataValid) {
console.log("The ice cream data is valid! 🍨");
} else {
console.error("The ice cream data is invalid:", ajv.errors);
}