How to Use Proxy for Validation in JavaScript
Use a
Proxy in JavaScript to intercept property assignments and validate values before they are set. Define a set trap in the proxy handler to check values and throw errors or reject invalid data.Syntax
A Proxy wraps a target object and intercepts operations like property setting. The set trap is a function that runs when a property is assigned a value.
It has this form:
target: the original object to wraphandler: an object with traps likesetset(target, property, value, receiver): trap called on property assignment
javascript
const proxy = new Proxy(target, { set(target, property, value, receiver) { // validation logic here target[property] = value; return true; // indicate success } });
Example
This example shows how to use a Proxy to validate that the age property is always a positive number before setting it.
javascript
const person = {}; const validator = { set(target, property, value) { if (property === 'age') { if (typeof value !== 'number' || value <= 0) { throw new Error('Age must be a positive number'); } } target[property] = value; return true; } }; const proxyPerson = new Proxy(person, validator); proxyPerson.age = 25; console.log(proxyPerson.age); // 25 try { proxyPerson.age = -5; // Throws error } catch (e) { console.log(e.message); }
Output
25
Age must be a positive number
Common Pitfalls
Common mistakes when using Proxy for validation include:
- Not returning
truefrom thesettrap, which can cause silent failures. - Forgetting to actually set the property on the target object.
- Throwing errors without try-catch, which can crash the program unexpectedly.
- Not handling all properties if validation is needed for multiple keys.
javascript
const obj = {}; const badValidator = { set(target, prop, value) { if (prop === 'score' && value < 0) { throw new Error('Score cannot be negative'); } // Missing target[prop] = value; and return true } }; const proxyObj = new Proxy(obj, badValidator); try { proxyObj.score = 10; // Does not set value console.log(proxyObj.score); // undefined } catch (e) { console.log(e.message); } // Correct way: const goodValidator = { set(target, prop, value) { if (prop === 'score' && value < 0) { throw new Error('Score cannot be negative'); } target[prop] = value; return true; } };
Output
undefined
Quick Reference
Tips for using Proxy for validation:
- Always return
truefrom thesettrap if the assignment succeeds. - Throw errors to reject invalid values clearly.
- Use
typeofand other checks to validate data types. - Remember to set the property on the target object inside the
settrap. - Wrap assignments in
try-catchwhen using proxies that throw errors.
Key Takeaways
Use a Proxy's set trap to intercept and validate property assignments.
Always set the property on the target and return true to confirm success.
Throw errors inside the set trap to reject invalid values clearly.
Wrap proxy property assignments in try-catch to handle validation errors safely.
Validate data types and values explicitly inside the set trap for robust checks.