pepsi
pepsi

Reputation: 321

Validating integer field in DTO

My spring boot application has the following DTO for request:

public class MyAwesomeDTO {

    @NotNull
    private Integer itemCount;
}

I want itemCount to be either 0, or in range [3, 10] . The latter can be validated with @Min(3) @Max(10), but how can I validate the "OR" condition?

Upvotes: 0

Views: 1418

Answers (1)

Wim Deblauwe
Wim Deblauwe

Reputation: 26858

There is a difference between itemCount being 0 or null. The @NotNull only guards against null, not 0.

The easiest way to accomplish what you need is to write a custom validator.

Start by creating a custom annotation to trigger the validation:

@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ItemCountValidator.class)
public @interface ValidItemCount {
    String message() default "Invalid item count";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Next, create the custom validator:

public class ItemCountValidator implements 
  ConstraintValidator<ValidItemCount, Integer> {

    @Override
    public void initialize(ValidItemCount validItemCount) {
    }

    @Override
    public boolean isValid(Integer itemCount,
      ConstraintValidatorContext cxt) {
        return itemCount != null && (itemCount == 0 || itemCount > 3 && itemCount < 10);
    }

}

Finally, update your DTO:

public class MyAwesomeDTO {

    @ValidItemCount
    private Integer itemCount;
}

Upvotes: 4

Related Questions