Proxy Traps For Runtime Validation
Intercept writes with a Proxy set trap so invalid assignments fail loudly at the mutation site instead of corrupting state silently.
Code
function validated(target, rules) {
return new Proxy(target, {
set(obj, key, value) {
const check = rules[key];
if (check && !check(value)) {
throw new TypeError('invalid value for ' + String(key) + ': ' + String(value));
}
obj[key] = value;
return true;
},
get(obj, key) {
if (key === '__rules') return Object.keys(rules);
return obj[key];
},
});
}
const account = validated({ id: 1, balance: 0 }, {
balance: (v) => typeof v === 'number' && v >= 0,
});
account.balance = 50;
console.log('balance:', account.balance);
try {
account.balance = -10;
} catch (error) {
console.log('rejected:', error.message);
}
console.log('still:', account.balance, '| guarded keys:', account.__rules);Output
Captured from a sandboxed run of this snippet in the build pipeline.
balance: 50
rejected: invalid value for balance: -10
still: 50 | guarded keys: [ 'balance' ]How it works
Count the function validated as the entire surface area of Proxy Traps For Runtime Validation.
Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.
The result is a fresh construction, so callers can keep their originals.
Watch out for
- The guard
key === '__rules'ends the run at once by triggering an earlyreturnwhen its condition holds.
Using it
The primary signature is function validated(target, rules)
Output lines are prefixed (balance:, rejected:, still:), making each step’s effect easy to spot.
Key statements
throw new TypeError('invalid value for ' + String(key) + ': ' + String(value));
if (key === '__rules') return Object.keys(rules);
return obj[key];
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does `validated` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Does the code validate its input?
- It throws `TypeError` before any real work runs, via the guard `key === '__rules'` — handle it at the call site or let it propagate deliberately.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `validated` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.