Validatoria
offers a validation function that expects an object and a specification object as parameters, that will return either an error or the validated object, which gets also rid off properties that are not specified in the specification.
Validator Function
async validateProperties(obj = {i: 'am the object to observe'}, specs = { i: { required: true, type: 'string' } }, name = 'MyOwnValidator') => { ...validatedObject }
Parameters
const specs = {
type: 'object' || 'array' || 'string' || 'number' || 'boolean'
required: true || false
format: *only for*:
- string: date, regex, mail, enum
- number: float, int
range: *only for*:
- string:
- format|date: [date_before, date_after]
- format|enum: [ ...enums]
- number: [number_min, number_max]
item: *only for objects and arrays* specs
default: any *default-type is not checked*
}
Examples:
String, number, date
await validateProperties(obj = {i: 'am', b: 3, c: '20105-28T10:04:00+0200'}, specs = {i: { required: true, type: 'string' }, b: { required: false, type: 'number' }, c: { required: true, type: 'date' }})
// @return
// {i: 'am', b: 3, c: '20105-28T10:04:00+0200'}
Objects, arrays, enums
await validateProperties(obj = { b: { c: 'd', e: 3}, c: ['string'] }, specs = { b: { type: 'object', required: true, item: { c: { required: true, type: 'string' }, e: { type: 'string', format: 'enum', required: false, range: [1, 2, 3] } } }, c: { type: 'array', required: true } })
// @return
// {b: {c: 'd', e: 3}, c: ['string']}
With default values
await validateProperties(obj = {}, specs = { a: {type: 'string', default: 'alright'}})
// @return
// {a: 'alright'}
WARNING!
If you provide both default: & require: the value will not throw an error if no value is given.
It will automatically set the default value.
i.e.: await validateProperties(obj = {}, specs = { a: {type: 'string', required: true, default: 'alright'}})
will add up to:
// @return
// { a: 'alright' }
Your own validate and transform Function
await validateProperties(obj = {b: 1}, specs = { transposeTo: async (obj) => obj.b.toString() })
// @return
// '1'