javahibernate-validatorjakarta-validation

Validating precision, scale of BigDecimal


I would like to do this:

import jakarta.validation.constraints.Decimal;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Getter;
import lombok.Setter;

import java.math.BigDecimal;

@Getter
@Setter
public class DepositRequestDto {

    @NotNull(message = "Must be present")
    @Positive(message = "Must be positive")
    @Decimal(precision = 22, scale = 2, message = "Must have at most 20 digits before, 2 digits after the decimal separator")
    private BigDecimal amount;
}

However, this code wouldn't compile. @Decimal doesn't exist.

How can I achieve the same effect with available options? Ideally without resorting to manual validation.

Hibernate Validator 8.0.2.Final.


Solution

  • @Digits fits perfectly:

    import jakarta.validation.constraints.Digits;
    import jakarta.validation.constraints.NotNull;
    import jakarta.validation.constraints.Positive;
    import lombok.Getter;
    import lombok.Setter;
    
    import java.math.BigDecimal;
    
    @Getter
    @Setter
    public class DepositRequestDto {
    
        @NotNull(message = "Must be present")
        @Positive(message = "Must be positive")
        @Digits(integer = 20, fraction = 2,
                message = "Must have at most 20 digits before, 2 digits after the decimal separator")
        private BigDecimal amount;
    }