Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Created May 20, 2024 19:58
Show Gist options
  • Save helabenkhalfallah/0977966aec44ac9c7cdc2424493484f8 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/0977966aec44ac9c7cdc2424493484f8 to your computer and use it in GitHub Desktop.
Proxy validation and sanitization
const validator = {
set(obj, prop, value, receiver) {
if (prop === "age") {
if (!Number.isInteger(value)) {
throw new TypeError("The age is not an integer");
}
if (value > 200) {
throw new RangeError("The age seems invalid");
}
}
// The default behavior to store the value
return Reflect.set(obj, prop, value, receiver);
},
};
const person = new Proxy({}, validator);
person.age = 100;
console.log(person.age); // 100
// person.age = "young"; // Throws an exception
// person.age = 300; // Throws an exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment