Search code examples
javavalidationswaggeropenapiopenapi-generator

OpenApi multipleOf in Java


I try to use the multipleOf-Property in my OpenApi spec but the generated java code doesn't contain any annotation or logic to validate the multipleOf. How could I use the multipleOf-Property to validate my JSON input? For the spec definition we use OpenApi 3.0.1

Here you can see the usage of multipleOf:

abc_field:
  type: number
  description: Description of ABC field
  minimum: 0
  maximum: 99999999999.99
  multipleOf: 0.01
  example: 200.57

Is there any solution to solve my validation problem? The validation api I use is javax.validation but there isn't any annotation for multipleOf.

The generated code for the abc_field looks like:

    public BetraegeKennzahlen abcField(BigDecimal abcField) {
        this.abcField = abcField;
        return this;
    }

    @ApiModelProperty(
        example = "200.57",
        value = "Description of ABC field"
    )
    @Valid
    @DecimalMin("0")
    @DecimalMax("99999999999.99")
    public BigDecimal abcField() {
        return this.abcField;
    }

    public void setAbcField(BigDecimal abcField) {
        this.abcField = abcField;
    }

Solution

  • The multipleOf property is not supported by openapi-generator https://github.com/OpenAPITools/openapi-generator/issues/2192

    You can add a custom constraint validator for your fields

    public class CustomValidator implements Validator {
       @Override
       public boolean supports(Class<?> aClass) {
           return GeneratedClass.class.isAssignableFrom(aClass);
       }
    
       @Override
       public void validate(Object o, Errors errors) {
           GeneratedClass generatedClass = (GeneratedClass)o;
           //validate
       }
    }
    

    And add a binder for that validator

        @InitBinder("generatedClass")
        protected  void initBinderForAvatarId(WebDataBinder binder) {
            binder.addValidators(new CustomValidator());
        }