Validation with Proxy
Learn to write a wrapper that validates property assignments with Proxy.
Validation with Proxy
A Proxy is a guard placed in front of a target object. Through the set trap, you can inspect a value before accepting the assignment and reject it if it is invalid.
A common pattern: in the set(target, prop, value) trap, check the type, range or format. If it breaks the rule, throw new TypeError('...'). The object then never enters an invalid state.
Collecting checks in one place applies the same control on every assignment, which catches bugs early.
Validation patterns
Validation patterns vary. Type checks run a test like typeof value === 'number'. Range checks look at whether a number stays inside a band: value >= 0 && value <= 120. Allowed-value checks let a property take only a value from an approved list.
Which one fits depends on the data. A range suits an age, an allowed list suits a role, a format suits an email. When validation fails, a meaningful message makes the bug easy to locate.
Exercise Reject negative age
Define a user object with an age: 0 property. Inside a handler, write a set(target, prop, value) trap: when prop === 'age' and value < 0, throw new TypeError('negative age'); otherwise run target[prop] = value and return true. Create proxy = new Proxy(user, handler). Assign proxy.age = 25 and log it with console.log(proxy.age).
Show example solution
const user = { age: 0 };
const handler = {
set(target, prop, value) {
if (prop === 'age' && value < 0) {
throw new TypeError('negative age');
}
target[prop] = value;
return true;
}
};
const proxy = new Proxy(user, handler);
proxy.age = 25;
console.log(proxy.age);
Test yourself
-
What happens if a set trap throws TypeError?
- The assignment is silently ignored
- The assignment still runs and the error is logged
- The assignment is skipped and the error propagates to the caller
- The object is frozen
Show answer
The assignment is skipped and the error propagates to the caller — Correct! When the set trap throws, the assignment is skipped and the error propagates normally.
-
Throw an error
const handler = { set(target, prop, value) { if (prop === 'age' && typeof value !== 'number') { ____; } target[prop] = value; return true; } };Show answer
const handler = { set(target, prop, value) { if (prop === 'age' && typeof value !== 'number') { throw new TypeError('type error'); } target[prop] = value; return true; } }; -
Match each trap to its operation
- set
- Assignment and validation
- get
- Property read
- has
- in operator
- deleteProperty
- delete operator