How to validate number string as digit with hibernate?

membersound picture membersound · Oct 23, 2013 · Viewed 21.7k times · Source

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?

Answer

Hardy picture Hardy · Oct 23, 2013

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.