Proxy Validation Example

Validate property values using Proxy.

Preview

Code

<script>
let user = {};

let proxy = new Proxy(user,{
  set(obj,prop,value){
    if(prop === "age" && value < 0){
      throw new Error("Invalid age");
    }
    obj[prop] = value;
    return true;
  }
});

proxy.age = 25;
console.log(proxy.age);
</script>

More JS Meta & Proxy Examples (7)