-2

I have a requirement to validate length for a BigDecimal object using JSR validators. It should contain at max of 10 characters.

Some valid examples:
123456789.0
12345.67890
12345.67
1.2345

Invalid examples:
123456789.0123
123.32131232

How can I achieve this using annotation ? Following @Size annotation is for String objects as per JSR documentation.

@Size(max = 10)
@Column(name = "totalPrice")
private BigDecimal totalPrice;
Chandra Prakash
  • 781
  • 4
  • 13
  • 23

2 Answers2

4

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.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
1

you can try

'@Digits(integer=,fraction=) or @DecimalMax(value = "9999999999.999", message = "The decimal value can not be more than 9999999999.999")'

this both should work.

if you want to know how to use these, then go with following urls

for @digit

https://www.owasp.org/index.php/Bean_Validation_Cheat_Sheet

for @decimalmax

http://www.c-sharpcorner.com/UploadFile/5fd9bd/javax-annotation-and-hibernate-validator-a-pragmatic-appro/

Vikash
  • 21
  • 7