It appears that the Hibernate NotEmpty
annotation does not result in an error for strings filled with whitespace (" "
). Only works for nulls or empty strings (ie: new String()
). Is there a workaround/fix for this?
Asked
Active
Viewed 6,190 times
5

Marcus Leon
- 55,199
- 118
- 297
- 429
3 Answers
15
@NotEmpty is used to check size rather than contents and applies to Collections as well as Strings. The functionality you're looking for is provided in @NotBlank which is specific to Strings and ignores trailing whitespace.

Ken Blair
- 337
- 3
- 4
-
I wish some of the Hibernate constraints had made it into JEE6. I find the default set of JEE6 constraints somewhat limited! – Muel Sep 14 '12 at 03:01
-
Note that `@NotEmpty` was added in version 4.1. For versions before 4.1, you will need to use a custom validator or `@Pattern`. See http://stackoverflow.com/a/17136803/2102634 for an longer explanation. – Rick Hanlon II Jun 16 '13 at 19:20
2
Replace your @NotEmpty with a @Pattern annotation that includes a regex expression that will fail on strings that are pure whitespace or empty (you may be able to include both @NotEmpty and @Pattern and simplify the regex that way). Or write a custom validator as described here.

Jherico
- 28,584
- 8
- 61
- 87