Skip to content

Instantly share code, notes, and snippets.

@sifat009
Last active January 19, 2022 07:59
Show Gist options
  • Save sifat009/4a1326eab1d4cb9d84f448ba2367bb43 to your computer and use it in GitHub Desktop.
Save sifat009/4a1326eab1d4cb9d84f448ba2367bb43 to your computer and use it in GitHub Desktop.
/**
* ℹ️ Topic: Use Proxy() to Set validation to javascript Object
* 📨 Contact for personalized training: sifathaque6@gmail.com 👈
*/
const userValidator = {
set(object, prop, value) {
const validProps = ['name', 'email'];
if (!validProps.includes(prop)) {
throw new Error(`Can't set ${prop}`);
} else {
// You can use other validation criteria here..
object[prop] = value;
return true;
}
},
};
class User {
constructor({ name, email }) {
this.name = name;
this.email = email;
return new Proxy(this, userValidator);
}
}
const user = new User({ name: 'Sifat', email: 'sifathaque6@gmail.com' });
user.password = '12345667';
// output: Can't set password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment