Design & Download
Your JS Library
in Seconds!!!

Snippet: check() - Object Validation

Written by Christopher West (cwest) on November 29, 2015.
function check(obj, criteria) {
  if (typeOf(criteria, 'Function')) {
    for (var k in obj) {
      if (has(obj, k)) {
        var v = obj[k];
        var result = criteria(v, typeOf(v));
        if (result !== true) {
          return 'Property "' + k + '":  ' + result;
        }
      }
    }
  }
  else {
    for (var k in criteria) {
      if (has(criteria, k)) {
        var v = criteria[k];
        var vt = typeOf(v);
        if (vt == 'String') {
          if (!typeOf(obj[k], v)) {
            return 'Property "' + k + '" was not of type ' + v + ' as expected';
          }
        }
        else if (vt == 'Function') {
          var result = v(obj[k], typeOf(obj[k]));
          if (result !== true) {
            return 'Property "' + k + '":  ' + result;
          }
        }
        else {
          if (!has(obj, k)) {
            return 'Property "' + k + '" was expected but not found';
          }
        }
      }
    }
  }
  return true;
}