You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
2.0 KiB
JavaScript

"use strict";
const errors = require("../errors");
const getValueType = require("../util/get-value-type");
module.exports = function createNumberValidatorFunction(options = {}, name = "<unknown>") {
let mayBeNaN = (options.mayBeNaN === true);
let mayBeInfinity = (options.mayBeInfinity === true);
let hasMinimum = (options.minimum != null);
let hasMaximum = (options.maximum != null);
if (hasMinimum && typeof options.minimum !== "number") {
throw new Error("Minimum value for number must be a number");
} else if (hasMaximum && typeof options.maximum !== "number") {
throw new Error("Maximum value for number must be a number");
} else if (hasMinimum && hasMaximum && options.minimum > options.maximum) {
throw new Error("Minimum value for number cannot be higher than maximum value");
} else {
return function validateNumber(value) {
/* TODO: More consistent error message format, with consistent property path metadata? */
if (typeof value !== "number") {
return new errors.ValidationError(`Expected a number, got ${getValueType(value)} instead`);
// return new errors.ValidationError(`Specified value for property '${name}' is not a number`, {
// value: value,
// property: name
// });
} else if (!mayBeNaN && isNaN(value)) {
return new errors.ValidationError(`Specified value for property '${name}' is NaN, but this is not allowed`, {
property: name
});
} else if (!mayBeInfinity && !isFinite(value)) {
return new errors.ValidationError(`Specified value for property '${name}' is an infinite value, but this is not allowed`, {
property: name
});
} else if (hasMinimum && value < options.minimum) {
return new errors.ValidationError(`Value for property '${name}' must be at least ${options.minimum}`, {
property: name
});
} else if (hasMaximum && value > options.maximum) {
return new errors.ValidationError(`Value for property '${name}' cannot be higher than ${options.maximum}`, {
property: name
});
} else {
return true;
}
};
}
};