Custom constraint is needed. That can be done roughly as follows:
Annotation:
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { BigDecimalLengthValidator.class})
public @interface BigDecimalLength {
int maxLength();
String message() default "Length must be less or equal to {maxLength}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
ConstraintValidator:
public class BigDecimalLengthValidator implements ConstraintValidator<BigDecimalLength, BigDecimal> {
private int max;
@Override
public boolean isValid(BigDecimal value, ConstraintValidatorContext context) {
return value == null || value.toString().length() <= max;
}
@Override
public void initialize(BigDecimalLength constraintAnnotation) {
this.max = constraintAnnotation.maxLength();
}
}
Usage:
@BigDecimalLength(maxLength = 3)
private BigDecimal totalPrice;
That should fill basic needs, for further tuning (messages in properties files, etc.) please check Creating custom constraints.