From a0cfb0c9d40578be610cb9d653b6986fee43679b Mon Sep 17 00:00:00 2001 From: cjihrig Date: Sun, 20 May 2018 11:15:00 -0400 Subject: [PATCH] lib: add validateInteger() validator This allows validation of integers that are not int32 or uint32. PR-URL: https://github.com/nodejs/node/pull/20851 Fixes: https://github.com/nodejs/node/issues/20844 Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell Reviewed-By: Benjamin Gruenbaum Backport-PR-URL: https://github.com/nodejs/node/pull/21171 Co-authored-by: Shelley Vohr --- lib/internal/validators.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/internal/validators.js b/lib/internal/validators.js index 556bfb2dc08f5f..aabe71ef33979a 100644 --- a/lib/internal/validators.js +++ b/lib/internal/validators.js @@ -13,7 +13,21 @@ function isUint32(value) { return value === (value >>> 0); } -function validateInt32(value, name) { +function validateInteger(value, name) { + let err; + + if (typeof value !== 'number') + err = new ERR_INVALID_ARG_TYPE(name, 'number', value); + else if (!Number.isSafeInteger(value)) + err = new ERR_OUT_OF_RANGE(name, 'an integer', value); + + if (err) { + Error.captureStackTrace(err, validateInteger); + throw err; + } +} + +function validateInt32(value, name, min = -2147483648, max = 2147483647) { if (!isInt32(value)) { let err; if (typeof value !== 'number') { @@ -53,6 +67,7 @@ function validateUint32(value, name, positive) { module.exports = { isInt32, isUint32, + validateInteger, validateInt32, validateUint32 };