Violations
description
get violated arguments for validation and assertion.
this helps design by contract
principle for publish API.
Usage
1, write your function, and decide a parameter type.
/** * @param * @param */ { // logic}
2, write a rule for parameter, and create validator.
let Violate = Violate; let rule = { if val === undefined return 'name is required'; } { if val === undefined return 'age is required'; if val < 0 return 'name should larger than 0'; } let validator = rule;
3, assert parameter before logic, for avoid programmer error.
/** * @param * @param */ { validator; // logic}
4, allow user to use validator before calling function.
{ let name = inputparamsname; let age = inputparamsage; let violations = validator; if violations violations; return; ;}
if validator.assert()
failed, it throws AssertionError
.
API
paramter
paramter for rules passed 3 args.
- val: value of param
- name: name of param
- _: utility function
let rule = { if _ return ` is required`; }
return errors
return single errors
let rule = { if _ return ` is required`; } let violations = rule;cosnole; // [ 'param is required' ]
return multiple errors
let rule = { let messages = ; if valuelength < 10 messages; if value messages; } let violations = rule;cosnole; // [ 'param should longer than 10', 'param should contain number' ]
no errors
let rule = { if _ return ` is required`; } let violations = rule;cosnole; // undefined
optional parameter
if parameter is optional, write rule like this.
let rule = { if _ return; // optional }
nested rules
if object was nested, write rule like this.
let target = a: 'a' b: c: 'c' d: 'd' ; let rules = { if v !== 'a' return 'a should "a"'; } b: // nested { if v !== 'c' return 'c should "c"'; } { if v !== 'd' return 'd should "d"'; }
utility function
- isString
- isFunction
- isBoolean
- isNumber (not NaN)
- isInteger
- isUndefined
- isArray
- isNull
- isEmpty (undefined or null or '')
- isObject (object not null, Array, Date, RegExp, Number)
- isDate
- isRegExp
- isError (instanceof Error)
- isEmail (based on whatwg regexp)
CHANGELOG
- v0.1.0: throw AssertionError if
assert()
failed instead of callingconsole.assert()
License
MIT