Hibernate Validator 4.1+ provides a custom string-only @NotBlank
annotation that checks for not null and not empty after trimming the whitespace. The api doc for @NotBlank
states:
The difference to NotEmpty is that trailing whitespaces are getting ignored.
If this isn't clear that @NotEmpty
is trimming the String before the check, first see the description given in the 4.1 document under the table 'built-in constaints':
Check that the annotated string is not null and the trimmed length is greater than 0. The difference to @NotEmpty is that this constraint can only be applied on strings and that trailing whitespaces are ignored.
Then, browse the code and you'll see that @NotBlank
is defined as:
@Documented
@Constraint(validatedBy=NotBlankValidator.class)
@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
@Retention(value=RUNTIME)
@NotNull
public @interface NotBlank{
/* ommited */
}
There are two things to note in this definition. The first is that the definition of @NotBlank
includes @NotNull
, so it's an extension of @NotNull
. The second is that it extends @NotNull
by using an @Constraint
with NotBlankValidator.class. This class has an isValid
method which is:
public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) {
if ( charSequence == null ) { //this is curious
return true;
}
return charSequence.toString().trim().length() > 0; //dat trim
}
Interestingly, this method returns true if the string is null, but false if and only if the length of the trimmed string is 0. It's ok that it returns true if it's null because, as I mentioned, the @NotEmpty definition also requires @NotNull.