node-adjuster
validate and adjust input values
Table of Contents
Introduction
All of web applications need handling input parameters, consists of following steps:
- existence check
- all required parameters exist?
- fill omittable parameters by default values
- type check
- e.g.,
typeof age === "number"
- cast them if needed;
"20"
(string) to20
(number)
- e.g.,
- domain check
- e.g.,
1 <= limit && limit <= 100
- revise them if needed;
0
to1
- e.g.,
node-adjuster
does all of them, by compact and highly readable code!
example
;; const constraints = // constraints for input id: adjuster // number, >=1 name: adjustermaxLength16 true // string, max 16 characters (trims if over) age: adjuster // number, integer (trims if decimal), >=0 email: adjuster // email state: adjuster // string, accepts only "active" and "inactive" classes: adjuster // array of number, separated by ",", ignores errors skills: adjuster // array of string, separated by ",", ignores errors credit_card: adjuster // numeric string, separated by "-", checks by Luhn algorithm remote_addr: adjuster // IPv4 remote_addr_ipv6: adjuster // IPv6 limit: adjuster // number, integer, omittable (sets 10 if omitted), >=1 (sets 1 if less), <=100 (sets 100 if greater) offset: adjuster // number, integer, omittable (sets 0 if omitted), >=0 (sets 0 if less);const input = // input values id: "1" name: "Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Ciprin Cipriano de la Santísima Trinidad Ruiz y Picasso" age: 205 email: "picasso@example.com" state: "active" classes: "1,3,abc,4" skills: "c,c++,javascript,python,,swift,kotlin" credit_card: "4111-1111-1111-1111" remote_addr: "127.0.0.1" remote_addr_ipv6: "::1" limit: "0";const expected = // should be adjusted to this id: 1 name: "Pablo Diego José" age: 20 email: "picasso@example.com" state: "active" classes: 1 3 4 skills: "c" "c++" "javascript" "python" "swift" "kotlin" credit_card: "4111111111111111" remote_addr: "127.0.0.1" remote_addr_ipv6: "::1" limit: 1 offset: 0; // Let's adjust!const adjusted = adjuster; // verificationassert;
That's all! No control flows! Isn't it cool?
For details, see basic usage.
Install
install from npm registry.
npm install -S adjuster
NOTE: package name is adjuster
, NOT node-adjuster
!
Loading
CommonJS
// foo.jsvar adjuster = ;
ES Modules
// foo.mjs;
TypeScript
// foo.ts;
Babel
ES6 Modules with// same as ES Modules!;
Reference
types and constants
AdjusterError
The AdjusterError
object represents an error when trying to adjust invalid value.
ambient declaration
properties
name | description |
---|---|
name |
"AdjusterError" |
message |
human-readable description of the error, including a string cause |
cause |
cause of adjustment error; see adjuster.CAUSE |
value |
value to adjust |
keyStack |
array consists of path to key name(for object) or index(for array) that caused error; for nested object or array |
See below example.
For detail about constraints / adjuster
, see basic usage
;; // {foo: Array<{bar: {baz: number}}>}const constraints = foo: adjuster;const input = foo: bar: baz: 1 bar: baz: 2 // index 2 bar: baz: "three" // ERROR! bar: baz: 4 ;assert;
adjuster.CAUSE
The cause of adjustment error.
For more information, see below examples.
adjuster.NUMERIC_STRING.CHECKSUM_ALGORITHM
Checksum algorithms for adjuster.numericString().checksum()
.
For more information, see numeric string.
adjuster.STRING.PATTERN
Regular expressions for adjuster.string().pattern()
.
For more information, see string.
basic usage
ambient declarations
adjuster.adjust(data, constraints[, onError])
Validate and adjust a input value.
data
An object to adjust; e.g., req.query
, req.body
(in Express)
data
will not be overwritten.
constraints
Constraints object for adjustment.
- key: the name of
data
to adjust value - value: the adjustment object; see below examples
onError(err)
Callback function for each errors. If no errors, this function will not be called.
If this parameter is omitted, adjuster.adjust()
throws AdjusterError
on first error and remaining adjustment process will be cancelled.
err
- an instance of
AdjusterError
ornull
err.keyStack
indicates path to key name that caused error:(string | number)[]
err
will benull
after all adjustment has finished and errors has occurredonError()
will no longer be called afternull
passed
- an instance of
- returns
- an adjuted value
undefined
means this key will not be included in returned object fromadjuster.adjust()
- return value of
onError(null)
is ignored
- throws
- an exception that will thrown from
adjuster.adjust()
- remaining adjustment processes will be cancelled
- an exception that will thrown from
examples
successful
For more information, see below references about adjuster.number()
, adjuster.string()
, and so on.
;; const constraints = id: adjuster name: adjustermaxLength16 true age: adjuster email: adjuster state: adjuster classes: adjuster // "true" means to ignore each errors skills: adjuster credit_card: adjuster remote_addr: adjuster remote_addr_ipv6: adjuster limit: adjuster offset: adjuster;const input = id: "1" name: "Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Ciprin Cipriano de la Santísima Trinidad Ruiz y Picasso" age: 205 email: "picasso@example.com" state: "active" classes: "1,3,abc,4" skills: "c,c++,javascript,python,,swift,kotlin" credit_card: "4111-1111-1111-1111" remote_addr: "127.0.0.1" remote_addr_ipv6: "::1" limit: "0";const expected = id: 1 name: "Pablo Diego José" age: 20 email: "picasso@example.com" state: "active" classes: 1 3 4 skills: "c" "c++" "javascript" "python" "swift" "kotlin" credit_card: "4111111111111111" remote_addr: "127.0.0.1" remote_addr_ipv6: "::1" limit: 1 offset: 0; const adjusted = adjuster;assert;
In TypeScript, use Generics for type-safe.
;; ;
error handling 1
adjust errors
;; const constraints = id: adjuster name: adjustermaxLength16 true email: adjuster;const input = id: 0 // error! (>= 1) name: "" // error! (empty string is not allowed) email: "john@example.com" // OK;const expected = id: 100 email: "john@example.com"; const adjusted = adjuster;assert; { return { if err === null // adjustment finished return; const key = errkeyStacks; // ["id"] if key === "id" // adjust to 100 on `id` error return 100; // remove otherwise };}
error handling 2
throw exception after finished
;; const constraints = id: adjuster name: adjustermaxLength16 true email: adjuster;const input = id: 0 // error! (>= 1) name: "" // error! (empty string is not allowed) email: "john@example.com" // OK; try adjuster;catch err // do something assert; { const messages = ; return { if err === null // adjustment finished; join key name as message throw messages; // append key name const key = errkeyStacks; // ["id"] messages; };}
error handling 3
catch a first error by omitting error handler
;; const constraints = id: adjuster name: adjustermaxLength16 true email: adjuster;const input = id: 0 // error! (>= 1) name: "" // error! (empty string is not allowed) email: "john@example.com" // OK; try const adjusted = adjuster;catch err // catch a first error assert;
error handling 4
when input value is not an object
NOTE: constraint
won't be checked because it's predictable; should be generated by programmer, not an external input
;; const constraints = {};const input = 123; try // `input` must be an object const adjusted = adjuster;catch err assert; assert;
boolean
ambient declarations
adjust(value[, onError])
Validate and adjust a input value.
If an error occurs, call onError
(if specified) or throw AdjusterError
(otherwise)
examples
// should be OKassert;assert; // should be adjustedassert;assert;assert;assert;assert;assert;assert;assert;assert;assert;assert;assert;assert;assert;assert;assert; // should cause errorassert;assert;assert;assert;
strict()
Enable strict type check.
HANDLE WITH CARE!
In URL encoding, all values will be treated as string.
Use this method when your system accepts ONLY JSON encoding (application/json
)
examples
// should cause errorassert;assert;assert;
acceptAllNumbers()
Accept all numbers, other than 0 / 1.
examples
// should be adjustedassert;assert;
default(value)
Accept undefined
for input, and adjust to value
.
If this method is not called, adjust(undefined)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptNull([value])
Accept a null
for input, and adjust to value
.
If this method is not called, adjust(null)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptEmptyString([value])
Accept an empty string(""
) for input, and adjust to value
.
If this method is not called, adjust("")
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
number
ambient declarations
adjust(value[, onError])
Validate and adjust a input value.
If an error occurs, call onError
(if specified) or throw AdjusterError
(otherwise)
examples
// should be OKassert; // should be adjustedassert;assert;assert; // should cause errorassert;assert;assert;
strict()
Enable strict type check.
HANDLE WITH CARE!
In URL encoding, all values will be treated as string.
Use this method when your system accepts ONLY JSON encoding (application/json
)
examples
// should be adjustedassert;assert; // should cause errorassert;assert;
default(value)
Accept undefined
for input, and adjust to value
.
If this method is not called, adjust(undefined)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptNull([value])
Accept a null
for input, and adjust to value
.
If this method is not called, adjust(null)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptEmptyString([value])
Accept an empty string(""
) for input, and adjust to value
.
If this method is not called, adjust("")
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptSpecialFormats()
Accept all special number formats; e.g., "1e+2"
, "0x100"
, "0o100"
, "0b100"
.
If this method is not called, the above examples causes AdjusterError
.
examples
// should be adjustedassert;assert;assert;assert; // should cause errorassert;
acceptFullWidth()
Accept full-width string; e.g., "1234.5"
, "1234.5"
.
If this method is not called, the above examples causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
integer([adjust])
Limit an input value to integer.
If adjust
is true, value will be adjusted to an integer.
examples
// should be adjustedassert;assert;assert;assert; // should cause errorassert;assert;assert;
only(...values)
Accept only values
.
If input value is not in values
, adjust()
method causes AdjusterError
.
examples
// should be OKassert; // should cause errorassert;
minValue(value[, adjust])
Limit minimum value to value
.
If input value is less than value
, adjust()
method returns value
(if adjust
is truthy) or causes AdjusterError
(falsy; default).
By default, value
equals Number.MIN_SAFE_INTEGER
.
examples
// should be OKassert;assert; // should be adjustedassert; // should cause errorsassert;assert;
maxValue(value[, adjust])
Limit maximum value to value
.
If input value is greater than value
, adjust()
method returns value
(if adjust
is truthy) or causes AdjusterError
(falsy; default).
By default, value
equals Number.MAX_SAFE_INTEGER
.
examples
// should be OKassert;assert; // should be adjustedassert; // should cause errorsassert;assert;
convert(converter)
/ map(mapper)
Convert input value into another value.
WARNING; map()
is deprecated. use convert()
.
examples
// should be adjustedassert; // should cause errorsassert;
string
ambient declarations
adjust(value[, onError])
Validate and adjust a input value.
examples
// should be OKassert; // should be adjustedassert;
strict()
Enable strict type check.
examples
// should be adjustedassert;assert; // should cause errorassert;assert;
default(value)
Accept undefined
for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
acceptNull([value])
Accept a null
for input, and adjust to value
.
If this method is not called, adjust(null)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptEmptyString([value])
Accept an empty string(""
) for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
trim()
Remove whitespace from both ends of input.
examples
// should be adjustedassert; // should cause errorassert;
only(...values)
Accept only values
.
examples
// should be OKassert;assert; // should cause errorassert;
minLength(length)
Limit minimum length of input string to length
.
examples
// should be OKassert; // should cause errorassert;
maxLength(length[, adjust])
Limit maximum length of an input string to length
.
If string length is greater than length
, adjust()
method truncates the length to length
(if adjust
is truthy) or causes AdjusterError
(falsy; default).
examples
// should be OKassert; // should be adjustedassert; // should cause errorassert;
pattern(pattern)
Specify acceptable pattern by regular expression.
You can also use adjuster.STRING.PATTERN
constants
constant | explanation |
---|---|
adjuster.STRING.PATTERN.EMAIL |
email address that follows RFC5321 / RFC5322 |
adjuster.STRING.PATTERN.HTTP |
HTTP/HTTPS URL |
adjuster.STRING.PATTERN.IPV4 |
IPv4 address |
adjuster.STRING.PATTERN.IPV6 |
IPv6 address |
adjuster.STRING.PATTERN.URI |
URI that follows RFC3986 |
examples
// should be OKassert;assert; // should cause errorassert;assert;
convert(converter)
/ map(mapper)
Convert input value into another value.
WARNING; map()
is deprecated. use convert()
.
examples
// should be adjustedassert; // should cause errorsassert;
numeric string
ambient declarations
adjust(value[, onError])
Validate and adjust input values.
examples
// should be OKassert; // should be adjustedassert;
default(value)
Accpet undefined
for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
acceptNull([value])
Accept a null
for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
acceptEmptyString([value])
Accept an empty string(""
) for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
separatedBy(separator)
Assume an input value is separated by separator
, and ignore them.
examples
// should be adjustedassert; // should cause errorassert;
fullWidthToHalf()
Convert full-width string to half-width; e.g., "1234"
.
If this method is not called, the above examples causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
joinArray()
Assume an input value is array, and join them.
This method is useful for following form.
<!-- "cc_number" will be passed in array --> Input credit card number: - - -
examples
// should be adjustedassert; // should cause errorassert;
minLength(length)
Limit minimum length of input string to length
.
examples
// should be OKassert; // should cause errorassert;
maxLength(length[, adjust])
Limit maximum length of an input string to length
.
examples
// should be OKassert; // should be adjustedassert; // should cause errorassert;
checksum(algorithm)
Check an input value by specified algorithm.
algorithm name | explanation | used by | constant | aliases |
---|---|---|---|---|
"luhn" |
Luhn algorithm | credit card | adjuster.NUMERIC_STRING.CHECKSUM_ALGORITHM.LUHN |
adjuster.NUMERIC_STRING.CHECKSUM_ALGORITHM.CREDIT_CARD |
"modulus10/weight3:1" |
Modulus 10 / Weight 3:1 | ISBN-13, EAN, JAN | adjuster.NUMERIC_STRING.CHECKSUM_ALGORITHM.MODULUS10_WEIGHT3_1 |
adjuster.NUMERIC_STRING.CHECKSUM_ALGORITHM.ISBN13 / adjuster.NUMERIC_STRING.CHECKSUM_ALGORITHM.EAN / adjuster.NUMERIC_STRING.CHECKSUM_ALGORITHM.JAN |
examples
// should be OKassert;assert;assert;assert;assert;assert; // should cause errorassert;
convert(converter)
/ map(mapper)
Convert input value into another value.
WARNING; map()
is deprecated. use convert()
.
examples
// should be adjustedassert; // should cause errorsassert;
ambient declarations
adjust(value[, onError])
Validate and adjust a input value.
examples
// should be OKassert; // dot-stringassert; // dot-stringassert; // quoted-stringassert; // quoted-stringassert;assert; // should cause errorassert;assert;assert;assert;assert;assert;assert;assert;
default(value)
Accept undefined
for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
acceptNull([value])
Accept a null
for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
acceptEmptyString([value])
Accept an empty string(""
) for input, and adjust to value
.
examples
// should be adjustedassert; // should cause errorassert;
trim()
Remove whitespace from both ends of input.
examples
// should be adjustedassert; // should cause errorassert;assert;
pattern(pattern)
Specify acceptable pattern by regular expression.
examples
// should be OKassert; // should cause errorsassert;
array
ambient declarations
adjust(value[, onError])
Validate and adjust input values.
examples
// should be OKassert; // should cause errorassert;assert;
default(value)
Accept undefined
for input, and adjust to value
.
If this method is not called, adjust(undefined)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptNull([value])
Accept a null
for input, and adjust to value
.
If this method is not called, adjust(null)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptEmptyString([value])
Accept an empty string(""
) for input, and adjust to value
.
If this method is not called, adjust("")
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
separatedBy(separator)
Assume an input value is string and separated by separator
.
If an input type is array, this method does nothing.
examples
// should be OKassert; // should be adjustedassert; // should cause errorassert;
toArray()
Convert an input value to array if not.
examples
// should be OKassert; // should be adjustedassert; // should cause errorassert;
minLength(length)
Limit minimum length of input array to length
.
examples
// should be OKassert; // should cause errorsassert;
maxLength(length[, adjust])
Limit maximum length of an input array to length
.
If array length is greater than length
, adjust()
method truncates the length to length
(if adjust
is truthy) or causes AdjusterError
(falsy; default).
examples
// should be OKassert; // should be adjustedassert; // should cause errorassert;
each(adjusterInstance, [ignoreEachErrors])
Apply constraints for each elements.
adjusterInstance
- Any above adjuster instance, e.g.,
adjuster.number()
,adjuster.string()
...adjuster.array()
!
- Any above adjuster instance, e.g.,
ignoreEachErrors
- If
true
, ignore the errors of each element. - default is
false
- If
examples
// should be adjustedassert; // should cause errorassert;
object
ambient declarations
adjust(value[, onError])
Validate and adjust input values.
examples
// should be OKassert; // should cause errorassert;assert;
default(value)
Accept undefined
for input, and adjust to value
.
If this method is not called, adjust(undefined)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptNull([value])
Accept a null
for input, and adjust to value
.
If this method is not called, adjust(null)
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
acceptEmptyString([value])
Accept an empty string(""
) for input, and adjust to value
.
If this method is not called, adjust("")
causes AdjusterError
.
examples
// should be adjustedassert; // should cause errorassert;
constraints(constraints)
Assume an input value is string and separated by separator
.
If an input type is array, this method does nothing.
examples
// should be OKconst constraints = a: adjuster b: adjuster;assert; // should be adjustedassert; // should cause errorassert;
Changelog
See CHANGELOG.md.