JavaScriptHard
How to use Proxy for validation?
Wrap an object in a Proxy with a set trap (and optionally defineProperty and deleteProperty traps) that checks each write against rules, throwing on invalid values and forwarding valid ones with Reflect.set, so the object can never hold invalid data.
Design
- Describe the rules as a schema: for each key, a validator function or type/range constraints.
- In
set(target, key, value, receiver):- reject unknown keys (optional, to catch typos);
- run the validator; throw a descriptive
TypeError/RangeErroron failure; - otherwise
return Reflect.set(target, key, value, receiver).
- Validate the initial data too, since the trap only sees writes made through the proxy.
- Optionally trap
deletePropertyto protect required fields, anddefinePropertysoObject.definePropertycannot bypass the rules.
Good uses
- Configuration objects edited at runtime.
- Form or settings models in small apps without a validation library.
- Debug builds that catch invalid state early.
- Enforcing read-only views (
setalways throws).
Limits
- Only writes through the proxy are checked; the original target object can still be modified directly, so keep it private.
- Nested objects need their own proxies (validate recursively).
- For API input and forms, schema libraries like Zod or Valibot are usually better: they produce typed results, error lists and work at boundaries rather than on every write.
Code example
js
1function createValidated(schema, initial = {}) {2 const check = (key, value) => {3 const rule = schema[key];4 if (!rule) throw new TypeError(`Unknown field "${String(key)}"`);5 const error = rule(value);6 if (error) throw new TypeError(`Invalid ${String(key)}: ${error}`);7 };89 const target = {};10 for (const [k, v] of Object.entries(initial)) check(k, v); // validate initial data too11 Object.assign(target, initial);1213 return new Proxy(target, {14 set(t, key, value, receiver) {15 check(key, value);16 return Reflect.set(t, key, value, receiver);17 },18 defineProperty(t, key, descriptor) {19 if ("value" in descriptor) check(key, descriptor.value); // block defineProperty bypass20 return Reflect.defineProperty(t, key, descriptor);21 },22 deleteProperty(t, key) {23 if (key === "email") throw new TypeError("email is required and cannot be deleted");24 return Reflect.deleteProperty(t, key);25 },26 });27}2829const userSchema = {30 name: (v) => (typeof v === "string" && v.trim().length >= 2 ? null : "at least 2 characters"),31 age: (v) => (Number.isInteger(v) && v >= 0 && v <= 150 ? null : "integer between 0 and 150"),32 email: (v) => (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? null : "not a valid email"),33};3435const user = createValidated(userSchema, { name: "Ada", age: 36, email: "ada@example.com" });36user.age = 37; // ok37console.log(user.age); // 373839for (const attempt of [() => (user.age = -5), () => (user.email = "nope"), () => (user.agee = 40), () => delete user.email]) {40 try {41 attempt();42 } catch (e) {43 console.log(e.message);44 }45}46// Invalid age: integer between 0 and 15047// Invalid email: not a valid email48// Unknown field "agee"49// email is required and cannot be deleted
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.