capypad
0 day streak
javascript / intermediate
Snippet

Dynamic Data Validation with Proxies

The Proxy object allows you to create a wrapper for another object, which can intercept and redefine fundamental operations for that object, such as property lookup, assignment, and enumeration. In this intermediate example, we use the 'set' trap to implement real-time validation logic on an object's properties.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const userSchema = {
set(target, prop, value) {
if (prop === 'age') {
if (typeof value !== 'number' || value < 0) {
throw new Error('Age must be a positive number');
}
}
target[prop] = value;
return true;
}
};
 
const user = new Proxy({}, userSchema);
user.age = 25; // Works
// user.age = -5; // Throws Error
Breakdown
1
const userSchema = { set(target, prop, value) { ... } }
Defines a handler object with a 'set' trap that intercepts property assignments.
2
if (prop === 'age') { ... }
Checks if the property being modified is 'age' to apply specific validation rules.
3
new Proxy({}, userSchema)
Creates a new Proxy that applies the schema logic to an empty target object.