Search code examples
javahibernate-validator

How to validate number string as digit with hibernate?


Which annotations would I have to use for Hibernate Validation to validate a String to apply to the following:

//should always have trimmed length = 6, only digits, only positive number
@NotEmpty
@Size(min = 6, max = 6)
public String getNumber { 
   return number.trim();
}

How can I apply digit validation? Would I just use @Digits(fraction = 0, integer = 6) here?


Solution

  • You could replace all your constraints with a single @Pattern(regexp="[\\d]{6}"). This would imply a string of length six where each character is a digit.