A simple asynchronous JSON validator with a chainable syntax.
npm install vlad
var validate = vlad.promise({
email: vlad.string,
location: vlad({
long: vlad.number.required.within(-180, 180),
lat: vlad.number.required.within(-90, 90)
}),
tags: vlad.array.of(vlad.string.within(3, 10))
});
validate(validObject).then(function(value) {
/*{
email: "me@example.com",
location: {
long: 70.235,
lat: 60.234
},
tags: ['foo', 'bar']
}*/
});
validate(invalidObject).catch(function(err) {
/* GroupValidationError {
message: "Invalid object.",
fields: {
email: FieldValidationError {message: '...'},
location: GroupValidationError {
message: 'Invalid object.',
fields: {
long: FieldValidationError {message: '...'}
}
},
tags: ArrayValidationError {
message: 'Invalid array.',
fields: [
undefined,
FieldValidationError {message: '...'},
undefined
]
}
}
}*/
});
router.post('/',
vlad.middleware('body', {
email: vlad.string.required.pattern(/.*@.*/)
}),
function(req, res) {
res.send(200);
}
);
router.use(function(err, req, res, next) {
if (err instanceof vlad.ValidationError) {
res.status(400).send(err.toJSON());
} else {
res.sendStatus(500);
}
});
var validate = vlad({
field: vlad.string.required
});
validate({ field: 'hello world' }).then( /* handle */ );
validate.field('hello world').then( /* handle */ )