wibe-validator
v1.0.5
Published
Wibe Validator helper
Downloads
1
Readme
Wibe Validator
It's a wrapper on top of JSON Schema Validator which should help you validate data match easier and faster without a need for any setup. Only two things are needed: schema
and data
.
How to use
Synchronous validation:
const WV = require('wibe-validator');
const validators = WV.Schemas.create({
user: require('./path/to/user_schemas.json')
});
class UserResource () {
static create(req) {
const validation = validators.user.validate(req.body);
if (!validation.valid) {
return {
status: 400,
// If validations ends with multiple errors, it will return only first
// To access them all, look up property validation.errors
message: validation.popError()
}
}
return createUser(data);
}
}
Asynchronous validation:
const WV = require('wibe-validator');
const validators = WV.Schemas.create({
user: require('./path/to/user_schemas.json')
});
class UserResource () {
static create(req) {
return validators.user
.validate(req.body)
.promise()
.then(data => createUser(data))
.catch(error => {
return {
status: 400,
message: error.message
}
})
}
}
Predefined Types
When you create your own schema you can use some predefined types:
- ObjectId - Mongo DB Object Id.
- UUID - Universally unique identifier
Example:
const WV = require('wibe-validator');
module.export = {
required: ['id'],
properties: {
id: WV.Types.ObjectId,
name: {
type: 'string'
},
};