Validate an Object that probably came from JSON

Parameter validation for builtins and custom types. Accepts  params and a schema and returns an array of Errors or false.

var validate = require('@smallwins/validate')

function hi(params, callback) {
  var schema = {
    'name':       {required:true,  type:Object},
    'name.first': {required:true,  type:String},
    'name.last':  {required:false, type:String}
  }
  var errors = validate(params, schema) 
  if (errors) {
    callback(errors)
  }
  else {
    callback(null, 'hi ' + params.first)
  }
}

// logs: null, hi brian
hi({name:{first:'brian', last:'leroux'}}, console.log)

// logs: [ [ReferenceError: missing required param name.first] ] 
hi({name:{}}, console.log)

considerations

  • For testing an Object that presumably came from a JSON payload
  • Thusly, primarily concerned with JSON value types: ObjectStringNumberArray and Boolean
  • Custom types are easily supported
  • Extra custom types bundled: EmailISODateRange and UUID
  • Designed to test keys and nested keys
  • Optionally validate required
  • Optionally validate min and max for StringNumber and Array builtin types (and easily implement for custom types / see DateRange for an example)

Read full article on GitHub

Subscribe to the Newsletter

Get our latest news,tutorials,guides,tips & deals delivered to your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.