json-strainer permite validar y transformar estructuras JSON.
INSTALACION
Usando npm:
npm install json-strainer
VALIDACION
USO BASICO
var jsonStrainer = require('json-strainer');
//Esquema de validacion
var schema = {
name: {type: 'string'},
age: {type: 'number'}
};
//JSON a validar
var data = {
name: "Darth Vader",
age: 90
};
jsonStrainer(data, schema, function (err, json){
if(err) console.log(err) //Manejar error
//Hacer algo mas con el json validado
console.log(json)
});
TIPOS DE DATOS SOPORTADOS
- string
- number
- date
- array
- object
- error
- regexp
- boolean
PROPIEDADES REQUERIDAS
var schema = {
name: {type: 'string', required: true}, //Requerido
age: {type: 'number'} //No requerido
}
VALIDACION MULTINIVEL
var schema = {
name: {type: 'string'},
account: {
type: 'object',
properties: {
email: {type: 'string'},
password: {type: 'number'}
}
}
}
VALIDACIONES PERSONALIZADAS
var validator = require('validator');
var schema = {
email: {
type: 'string',
validators: [
{
validate: validator.isEmail,
message: 'Formato incorrecto'
}
]
}
};
TRANSFORMACION
var schema = {
email: {
type: 'string',
path: 'property_1'
}
};
//Resultado
//{ property1: { email: 'vader@gmail.com' } }
PREFIJOS
var schema = {
email: {type: 'string', prefix: 'account'}
};
//Resultado
//{'account.email': email@gmail.com}