Hibernate Validator 4.1+ provides a custom @NotBlank annotation string that checks for non-null and non-empty after trimming a space. The api doc for @NotBlank states:
The difference from NotEmpty is that trailing spaces are ignored.
If it is not clear that @NotEmpty truncates the string before validation, first look at the description given in document 4.1 under the table 'built -in constaints' :
Make sure that the annotated string is non-zero and the trimmed length is greater than 0. The difference with @NotEmpty is that this restriction can only be applied to strings and that trailing spaces are ignored.
Then review the code and you will 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{ }
There are two things in this definition. Firstly, the definition of @NotBlank includes @NotNull , so this is an extension of @NotNull . Secondly, it extends @NotNull using @Constraint with NotBlankValidator.class. This class has an isValid method, which:
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 is normal that it returns true if it is null, because, as I mentioned, the definition of @NotEmpty @NotNull is also required.