JavaScript Tutorial ✦
Proxy for Input Validation
Using Proxy to validate object property assignments.
const validator = {
set(target, prop, value) {
if (prop === 'age' && value < 0) throw 'Invalid age';
target[prop] = value;
}
};
const user = new Proxy({}, validator);
user.age = 25; // Valid
// user.age = -5; // Throws error