Java Digits Validation
Solution 1
As you need the 6 digits, I think you should use a String to the property. If in some situations you need it as int, you make a
public int getIdOrder(){ return Integer.parseInt(idOrder);}
On the String you can use pattern validation. It would be somethind like this:
@Pattern(regexp="\\d{6}")
private String idOrder;
Another option, is keep the idOrder a int and make a getter for the string:
public String getIdOrgetAsString(){
String s = "000000" + idOrder;
return s.substring(s.length() - 6);
}
Anyway, there are some options.
Solution 2
Are you sure your validation works at all?
The Hibernate documentation says:
Check whether the property is a number having up to integer digits and fraction fractional digits. 1
What means exactly 6 digits? Are leading zeros supported? Or should the number be between 100.000 and 999.999. In the first case, I guess your number should be a String (with @Length), and in the second case, I guess you should use @Min and @Max.
Renato Shumi
Updated on December 21, 2020Comments
-
Renato Shumi over 3 years
I'm using validation in a int attribute:
@Digits(integer=6,fraction=0) private Integer idOrder;
But I wanted this attribute has exactly 6 digits.
How can I do that? (Using JSP+Spring+Hibernate)
-
Renato Shumi about 11 yearsIt is not working. Exactly 6 digits I mean 6 numbers, like: 000000, 020123, 123452,...
-
Stefan Jansen about 11 yearsIn that case, using a String with @Length should work. If it does not, I guess your validation does not work at all. Or does a String not fit in your use case? And so, why not?
-
Renato Shumi about 11 yearsI must use int ou Integer. @Lenght just works with Strings.
-
Brendan Long about 11 years@RenatoShumi An
int
never has leading digits, so your code is already correct as far as I can tell.