From fd0bbb83c969ede5649f3d8bdc4ec0c8b7f94da3 Mon Sep 17 00:00:00 2001 From: Mark Moffat Date: Sat, 16 Nov 2019 12:52:54 +1030 Subject: [PATCH] Added custom schema validation formats --- lib/schema.js | 14 +++++++++++++- lib/schemas/{newCustomer.json => customer.json} | 4 ++-- lib/schemas/editProduct.json | 3 ++- lib/schemas/newProduct.json | 3 ++- 4 files changed, 19 insertions(+), 5 deletions(-) rename lib/schemas/{newCustomer.json => customer.json} (93%) diff --git a/lib/schema.js b/lib/schema.js index 8138e07..03d9e46 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -10,10 +10,22 @@ const addSchemas = () => { const fileData = JSON.parse(fs.readFileSync(file, 'utf-8')); ajv.addSchema(fileData, path.basename(file, '.json')); }); + + // Email format + const emailRegex = /^([\w-.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; + ajv.addFormat('emailAddress', emailRegex); + + // Amount format + const amountRegex = /^[1-9]\d*(\.\d+)?$/; + ajv.addFormat('amount', amountRegex); }; const validateJson = (schema, json) => { - return ajv.validate(schema, json); + const result = ajv.validate(schema, json); + return{ + result, + errors: ajv.errors + }; }; module.exports = { diff --git a/lib/schemas/newCustomer.json b/lib/schemas/customer.json similarity index 93% rename from lib/schemas/newCustomer.json rename to lib/schemas/customer.json index 8c5927b..7d3d10c 100644 --- a/lib/schemas/newCustomer.json +++ b/lib/schemas/customer.json @@ -1,10 +1,10 @@ { - "$id": "newCustomer", + "$id": "customer", "type": "object", "properties": { "email": { "type": "string", - "format": "email" + "format": "emailAddress" }, "firstName": { "type": "string" diff --git a/lib/schemas/editProduct.json b/lib/schemas/editProduct.json index 24b86fd..eed3fad 100644 --- a/lib/schemas/editProduct.json +++ b/lib/schemas/editProduct.json @@ -12,7 +12,8 @@ "type": "string" }, "productPrice": { - "type": "number" + "type": "number", + "format": "amount" }, "productDescription": { "type": "string" diff --git a/lib/schemas/newProduct.json b/lib/schemas/newProduct.json index 496a399..8339d06 100644 --- a/lib/schemas/newProduct.json +++ b/lib/schemas/newProduct.json @@ -9,7 +9,8 @@ "type": "string" }, "productPrice": { - "type": "number" + "type": "number", + "format": "amount" }, "productDescription": { "type": "string"