Skip to content

Instantly share code, notes, and snippets.

@rambabusaravanan
Created June 15, 2018 06:59
Show Gist options
  • Save rambabusaravanan/42c4b919449342c02a28da79ce046c7c to your computer and use it in GitHub Desktop.
Save rambabusaravanan/42c4b919449342c02a28da79ce046c7c to your computer and use it in GitHub Desktop.
jsonschema validation with custom display name
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);
@rambabusaravanan
Copy link
Author

Output is

[
  'X Coordinate is required',
  'address.city is required',
  'State / Province is required',
  'requires property "y"'
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment