NPM Module to convert predefined JSON into Joi validation schema dynamically.
const JoiSchemaBuilder = require('ak-json-to-joi');
const joiSchemaJSON = {
"name":{
"org": {
"$type":"string",
"required": true
},
"nick": {
"$type":"string",
"required": true
}
},
"number":{
"$type":"number",
"optional": true
},
"date": {
"$type": "timestamp",
"timestamp": 'javascript'
}
};
const json = {
"name": {
"org": "arshad",
"nick": "ars"
},
"number": "999999999",
"date": "1311110000000"
};
let JoiValidationSchema = JoiSchemaBuilder.build(joiSchemaJSON);
// Validating payjoload with JOI Schema
let result = Joi.validate(yourPayloadJSON, JoiValidationSchema)
if (result.error) {
// Validation failed
} else {
// Validation passed
}
Currently the library supports these types
- string
- number
- array
- object
- boolean
- minLength: Value must be an integer
- maxLength: Value must be an integer
- optional: Boolean flag (true / false)
- required: Boolean flag (true / fallse)
- regex: Regex Pattern
- default: Default value, depends on the type defined
'type' and 'array' key in validation json should be prefixed with '$' symbol on missing $ symbol your validation might not work.
Interested in contributing to this library. Read here on how to get started