Skip to content

Commit

Permalink
lib: support ranges in validateInt32()
Browse files Browse the repository at this point in the history
This commit adds minimum and maximum value checks to the
validateInt32() validator.

PR-URL: #20588
Fixes: #20498
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Weijia Wang <starkwang@126.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>

Backport-PR-URL: #21172
  • Loading branch information
cjihrig authored and targos committed Jun 13, 2018
1 parent 2ffb9d6 commit 36e5100
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/internal/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,22 @@ function validateInteger(value, name) {
}

function validateInt32(value, name, min = -2147483648, max = 2147483647) {
// The defaults for min and max correspond to the limits of 32-bit integers.
if (!isInt32(value)) {
let err;
if (typeof value !== 'number') {
err = new ERR_INVALID_ARG_TYPE(name, 'number', value);
} else if (!Number.isInteger(value)) {
err = new ERR_OUT_OF_RANGE(name, 'an integer', value);
} else {
// 2 ** 31 === 2147483648
err = new ERR_OUT_OF_RANGE(name, '> -2147483649 && < 2147483648', value);
err = new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
}
Error.captureStackTrace(err, validateInt32);
throw err;
} else if (value < min || value > max) {
const err = new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
Error.captureStackTrace(err, validateInt32);
throw err;
}
}

Expand Down

0 comments on commit 36e5100

Please sign in to comment.