I am tying to apply custom validations on each item of JS object according to name of the item. for ex, age_int should be of type int else it should throw error and If try to edit with wrong datatype, it should throw error.
const obj { age_int: 2, name string: "adam", job: null, }
const validatingobject = typecheck(obj)
validatingobject.age_int = 2.25 // throws error
validatingobject.age_int = 2
validatingobject.job = "fireman"
validatingobject.address_string = 20 // throws error
Its not the complete code, you should complete as your needs:
function typecheck(obj){
for (let key in obj) {
if (key.includes("int") && Number.isInteger(obj[key])){
console.log(key, obj[key], "is int");
}
// you need to complete by your needs
}
}
Another option:
const typecheck = Object.freeze(
// Create new objecct with NO prototype: null
Object.create(null, {
// 'a_int' set/get
a_int: {
get() {
// Check: Symbol existence
return this[Symbol.for('a_int')]
},
set(val) {
if(!Number.isInteger(val))
throw new DOMException("not int")
this[Symbol.for('a_int')] = val;
}
}
})
);