JSON Schema Validator. Validate max digits in number

63 Views Asked by At

is there any way to validate number of digits in number in JSON schema validator (https://mvnrepository.com/artifact/com.networknt/json-schema-validator).

My number should have max 5 digits and no more than 3 decimal places. In my DTO this number is BigDecimal. I know that number of decimal places I can achieved with "multiplyOf" validator.

Maybe I should write own validator in JSON Schema Validator lib to validate max digits? If yes, how to do that?

1

There are 1 best solutions below

0
jareon On

You can use exclusiveMaximum to validate the digits.

{
  "type": "number",
  "exclusiveMaximum": 100000,
  "multipleOf": 0.001
}

Given the code

String schemaData = "{\r\n"
                + "  \"type\": \"number\",\r\n"
                + "  \"exclusiveMaximum\": 100000,\r\n"
                + "  \"multipleOf\": 0.001\r\n"
                + "}";
JsonSchema schema = JsonSchemaFactory.getInstance(VersionFlag.V202012).getSchema(schemaData);
System.out.println(schema.validate("99999.999", InputFormat.JSON));
System.out.println(schema.validate("100000", InputFormat.JSON));
System.out.println(schema.validate("99999.0001", InputFormat.JSON));

The output is

[]
[$: must have an exclusive maximum value of 100000]
[$: must be multiple of 0.001]