Marcus Leon
Marcus Leon

Reputation: 56679

Hibernate validator NotEmpty trim issue

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?

Upvotes: 6

Views: 6587

Answers (3)

DavidA
DavidA

Reputation: 4184

@NotBlank is the way to test string lengths with an implicit trim call.

Upvotes: 12

Ken Blair
Ken Blair

Reputation: 347

@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.

Upvotes: 16

Jherico
Jherico

Reputation: 29240

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.

Upvotes: 2

Related Questions