Created
June 15, 2018 06:59
-
-
Save rambabusaravanan/42c4b919449342c02a28da79ce046c7c to your computer and use it in GitHub Desktop.
jsonschema validation with custom display name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const validate = require('jsonschema').validate; | |
let schema = { | |
"type": "object", | |
"properties": { | |
"x": { | |
"display": "X Coordinate", // This is some extra field that we give for our purpose | |
"type": "number", | |
"required": true // error says like 'is required' | |
}, | |
"y": { | |
"display": "Y Coordinate", | |
"type": "number", | |
}, | |
"address": { | |
"type": "object", | |
"properties": { | |
"city": { | |
"type": "string", | |
"required": true | |
}, | |
"state": { | |
"display": "State / Province", | |
"type": "string", | |
"required": true | |
} | |
}, | |
"required": true | |
} | |
}, | |
"required": [ | |
"y" // error says like 'requires property "y"' | |
] | |
} | |
let json = { | |
// "x": "34", | |
// "x": 34, | |
// "y": false, | |
"address": { | |
// "city": "Madurai" | |
} | |
} | |
let result = validate(json, schema); | |
console.log(JSON.stringify(result, null, 2)); | |
// length of "instance." is 9 | |
let errorMessages = result.errors.map(e => e.schema.display ? (e.schema.display + ' ' + e.message) : e.stack.substr(9)) | |
console.log(errorMessages); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is