Javascript - Proxy and validation

Introduction

Proxies is useful for validation.

We can validate the passed value using set handler.

The following code checks age for validation.

Demo

const voterValidator = { 
    set: function(obj, prop, value) { 
        if (prop === "age") { 
            if (!Number.isInteger(value)) { 
                throw new TypeError("Input age is not an integer"); 
            } //from w  ww. j  a  va 2  s  .c  o  m
            if (value < 18) { 
                throw new RangeError("Input age seems invalid"); 
            } 
        } else if (prop === "residency") { 
            if (value === false) { 
                throw new Error("Residency is mandatory to vote"); 
            } 
        } 
        // The default behavior to store the value 
        obj[prop] = value; 

        // Indicate success 
        return true; 
    } 
}; 

const person = new Proxy({}, voterValidator); 

person.age = 23; 
person.residency = false;     // Throws an exception 
person.age = "young";         // Throws an exception 
person.age = 200;             // Throws an exception

Result

Related Topic