Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The ValidatorContext.prototype.validateMultipleOf function is not working properly for negative numbers #281

Open
simonmrog opened this issue Jun 12, 2024 · 0 comments

Comments

@simonmrog
Copy link

simonmrog commented Jun 12, 2024

The calculation of the remainder in the validateMultipleOf function (line 776 in the tv4.js file) is wrong for the case in which the data is a negative number, in which case the modulus changes sign and the function returns null instead of returning the corresponding error.

The reason is that the [CLOSE_ENOUGH_LOW, CLOSE_ENOUGH_HIGH] interval validation fails since CLOSE_ENOUGH_LOW >= 0 and for negative numbers remainder <= 0.
One fix to this issue may be to use the absolute value in the remainder to consider both signs:

ValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) {
	var multipleOf = schema.multipleOf || schema.divisibleBy;
	if (multipleOf === undefined) {
		return null;
	}
	if (typeof data === "number") {
		var remainder = Math.abs((data / multipleOf) % 1);
		if (remainder >= CLOSE_ENOUGH_LOW && remainder < CLOSE_ENOUGH_HIGH) {
			return this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}, '', '', null, data, schema);
		}
	}
	return null;
};

With this implementation (proposed in PR #282) the function returns the same error for a number both positive and negative with the same schema.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant