@NotNull://CharSequence, Collection, Map 和 Array 對象不能是 null, 但能夠是空集(size = 0)。 @NotEmpty://CharSequence, Collection, Map 和 Array 對象不能是 null 而且相關對象的 size 大於 0。 @NotBlank://String 不是 null 且去除兩端空白字符後的長度(trimmed length)大於 0。
@Constraint(validatedBy = {NotNullValidator.class})
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { return object != null; }
@NotNull @Size(min = 1)
也就是說,@NotEmpty除了@NotNull以外還須要保證@Size(min=1),這也是一個註解,這裏規定最小長度等於1,也就是相似於集合非空。
javascript
@NotNull @Constraint(validatedBy = {NotBlankValidator.class})
if ( charSequence == null ) { //curious return true; } return charSequence.toString().trim().length() > 0;
有意思的是,當一個string對象是null時方法返回true,可是當且僅當它的trimmed length等於零時返回false。即便當string是null時該方法返回true,可是因爲@NotBlank還包含了@NotNull,因此@NotBlank要求string不爲null。
css
String name = null; @NotNull: false @NotEmpty: false @NotBlank: false String name = ""; @NotNull: true @NotEmpty: false @NotBlank: false String name = " "; @NotNull: true @NotEmpty: true @NotBlank: false String name = "Great answer!"; @NotNull: true @NotEmpty: true @NotBlank: true
1、經常使用的校驗註解
(1)經常使用標籤 @Null 被註釋的元素必須爲null @NotNull 被註釋的元素不能爲null @AssertTrue 被註釋的元素必須爲true @AssertFalse 被註釋的元素必須爲false @Min(value) 被註釋的元素必須是一個數字,其值必須大於等於指定的最小值 @Max(value) 被註釋的元素必須是一個數字,其值必須小於等於指定的最大值 @DecimalMin(value) 被註釋的元素必須是一個數字,其值必須大於等於指定的最小值 @DecimalMax(value) 被註釋的元素必須是一個數字,其值必須小於等於指定的最大值 @Size(max,min) 被註釋的元素的大小必須在指定的範圍內。 @Digits(integer,fraction) 被註釋的元素必須是一個數字,其值必須在可接受的範圍內 @Past 被註釋的元素必須是一個過去的日期 @Future 被註釋的元素必須是一個未來的日期 @Pattern(value) 被註釋的元素必須符合指定的正則表達式。 @Email 被註釋的元素必須是電子郵件地址 @Length 被註釋的字符串的大小必須在指定的範圍內 @NotEmpty 被註釋的字符串必須非空 @Range 被註釋的元素必須在合適的範圍內