/**
jPack type_checks Demo
https://htmlguyllc.github.io/jPack/#typechecks
Perform object validation in a single line.
isDataObject accepts these parameters:
jpack.type_checks.isDataObject(object_to_validate, expect_keys, require_all_expected_keys, block_other_keys, throw_error)
*/
//show the results in HTML
function expected(msg) {
jpack.dom.getElement('results').innerHTML += '<hr>Expected! ' + msg;
}
function unexpected(msg) {
jpack.dom.getElement('results').innerHTML += '<hr>Unexpected! ' + msg;
}
//a sample object
var object = {
id: 1,
name: 'Bob',
something_new: 'I\'m something unexpected'
};
//will fail
try {
//must contain both id and name, cannot contain anything else
jpack.type_checks.isDataObject(object, ['id', 'name'], true, true, true);
unexpected('valid');
} catch (e) {
expected(e);
}
//will fail
try {
//very strict! must contain id, name, and email - cannot contain anything else
jpack.type_checks.isDataObject(object, ['id', 'name', 'email'], true, true, true);
unexpected('valid');
} catch (e) {
expected(e);
}
//will fail
try {
//must contain at least one id, name, or email - cannot contain anything else
jpack.type_checks.isDataObject(object, ['id', 'name', 'email'], false, true, true);
unexpected('valid');
} catch (e) {
expected(e);
}
//will succeed
try {
//must contain at least one id or name - can contain other things
jpack.type_checks.isDataObject(object, ['id', 'name'], false, false, true);
expected('success');
} catch (e) {
unexpected(e);
}
/**
*
* Now let's test it in a real world scenario
*
* Let's say we have a User class which is populated during instantiation and you want to make sure
* someone didn't make a mistake and pass any variables that shouldn't have been
*
*/
class User {
constructor(data) {
//must contain at least one (id,name,email), cannot contain anything else
jpack.type_checks.isDataObject(data, ['id', 'name', 'email'], false, true, true);
//set each...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.