jPack type_checks Demo

Javascript component for validating an object

by Shane Stebner

HTML

<script src="https://htmlguyllc.github.io/jPack/dist/jpack.bundled.min.js"></script>
<h1>Results:</h1>
<results></results>

JavaScript

/**
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...