Skip to content

Wrong validation of MultipleOfValidator #421

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

Closed
ubergrohman opened this issue Jul 5, 2021 · 3 comments
Closed

Wrong validation of MultipleOfValidator #421

ubergrohman opened this issue Jul 5, 2021 · 3 comments

Comments

@ubergrohman
Copy link
Contributor

When using json schema with multipleOf restriction

"amount": {
    "type": "number",
    "multipleOf": 0.0000001,
    "exclusiveMaximum": 1000000000000
}

and large value (for example "amount"=999999999.12345678) MultipleOfValidator uses node.doubleValue() for getting node value and looses precision. Jackson DeserializationFeature flag USE_BIG_DECIMAL_FOR_FLOATS set to true.
Expected error is "amount: must be multiple of 1.0E-7"

@ubergrohman
Copy link
Contributor Author

Way to fix
com.networknt.schema.MultipleOfValidator.validate

public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
        debug(logger, node, rootNode, at);

        if (node.isNumber()) {
            double nodeValue = node.doubleValue();
            if (divisor != 0) {
                // convert to BigDecimal since double type is not accurate enough to do the division and multiple
                BigDecimal accurateDividend = node.isBigDecimal() ? node.decimalValue() : new BigDecimal(String.valueOf(nodeValue));
                BigDecimal accurateDivisor = new BigDecimal(String.valueOf(divisor));
                if (accurateDividend.divideAndRemainder(accurateDivisor)[1].abs().compareTo(BigDecimal.ZERO) > 0) {
                    return Collections.singleton(buildValidationMessage(at, "" + divisor));
                }
            }
        }

        return Collections.emptySet();
    }

@stevehu
Copy link
Contributor

stevehu commented Jul 6, 2021

@ubergrohman It makes sense to convert to BigDecimal to do the calculation. Could you please submit a PR with your fix? Github gives credit where credit is due :)

@ubergrohman
Copy link
Contributor Author

@stevehu Please review #422.

@stevehu stevehu closed this as completed Jul 6, 2021
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

2 participants