Skip to content

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

@simonmrog

Description

@simonmrog

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions