Simple object validation

Tags:
Date:

Monday 01/08/2022

You can use Proxy to add simple validation to your objects.

Example:

const car = {
    brand: 'Ford',
    year: 2022,
    drive: false
}

const carProxy = new Proxy(car, {
    get: (obj, prop) => {
        if (prop === 'drive') {
            console.log(`This car can only fly`)
        } else {
            console.log(`The value of ${prop} is ${obj[prop]}`)
        }
    },
    set: (obj, prop, value) => {
        if (prop === 'year' && typeof value !== 'number') {
            console.log(`Sorry, you can only pass numbrs for year.`)
        }
    },
})

console.log(carProxy.drive) // This car can only fly
carProxy.year = '2023' //Sorry, you can only pass numbrs for year.

This is very basic implementation but you can go pretty wild with it.

© 2023 Vadim Alakhverdov