2.2.1 • Published 3 years ago

@tailored-apps/validatoria v2.2.1

Weekly downloads
5
License
ISC
Repository
gitlab
Last release
3 years ago

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.

async validateProperties(obj = {i: 'am the object to observe'}, specs = { i: { required: true, type: 'string' } }, name = 'MyOwnValidator') => { ...validatedObject }
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*
}
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'}
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']}
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' }
await validateProperties(obj = {b: 1}, specs = { transposeTo: async (obj) => obj.b.toString() })

// @return
// '1'
2.2.1

3 years ago

2.2.0

3 years ago

2.1.0

4 years ago