Forked from sifat009/proxy-to-validate-javascript-object.js
Created
January 19, 2022 07:59
-
-
Save hunghg255/ba3efcd0c67efe5a4d060f249ebbe25f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ℹ️ 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