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.

JavascriptSecurity Boundaries

Code

javascriptsnippet
29 lines
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 early return when 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

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.