muster
muster is a library for quickly and easily validating javascript objects. It is especially designed for JSON API input validation, but is acceptable as a more general-purpose solution as well. muster does not pollute native prototypes or the global namespace.
Example usage:
Specifying required and optional fields
var muster = ;var m = var doc = firstname : 'Joe' lastname : 'Strummer'var error = mif error console; else console;// outputs "valid!"
The anatomy of an error object:
var muster = ;var m = var doc = firstname : 'Joe'var error = m;console;// outputs: { type: 'MissingAttribute',// message: 'A key named \'lastname\' is required but was not found.',// detail: 'lastname' }// notice that they all have type, message, and detail fields.
Key Validators (for validating individual keys of an object):
var muster = ;var m = console;console;// outputs:// false// { type: 'InvalidAttribute',// message: 'Key \'firstname\' was not in the correct format.',// detail: 'Johnny5' }
Key Validators Examples:
mustBeA
var m = // can match Number, String, Boolean, or Arrayconsole;
mustBeLessThan
var m = console;
mustBeGreaterThan
var m = console;
mustHaveLength
// for strings and arraysvar m = console;
mustEqual
var m = console;
mustMatch
var m = console;
mustBeOneOf
// for enumerationsvar m = console;
mustBeAnEmailAddress
// VERY loose acceptance, to avoid false-negativesvar m = console;
mustBeADateString
// determine if it's a RFC3339 / ISO 1806 datestring var m = console;
mustPass
// for user-defined matchersvar m = console;
mustPassMuster
// takes a muster object for sub-objects.var nameMuster = var m = console;
Chaining Validators:
Validators can be chained.
var muster = ; var m = console;
Alternative ways to get errors
errors()
The errors() method will return all errors, rather than just the first one.
var muster = ; var m = console; // output: 0
check()
The check() method will throw the error as an exception, rather than returning it.
var muster = ; var m = try m); console catch error console // output: success!
checkAll()
The checkAll() method will throw all errors in array as an exception, rather than returning it.
var muster = ; var m = try m); console catch errors console console // output: success!
Think muster is missing an obvious validator?
I'd love to hear suggestions or get pull requests, but in the meantime you can still add it to the keyvalidator prototype at runtime...
var muster = ; var validator = musterkeyValidatorPrototype; // just add your own validations to the prototype validator{ // the validation message... thismessage = "Key '" + thiskeyname + "' must be the colour " + colour + "."; this{ // the validation function return val == colour; }; thismuster // registers the key validator return thismuster; // necessary for chaining } var error =