Hibernate Validator 4.1+ 提供了一个自定义的纯字符串注解,在修剪空白后@NotBlank
检查 not null 和 not empty 。状态的 api 文档: @NotBlank
NotEmpty 的不同之处在于尾随空格被忽略。
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.