Constraints: Null, Empty, and Blank.

As I see there is some confusion related to validation annotations usage in Java. Let’s see a quick example of the three most confusing annotations from the Hibernate Validator.

@NotNull

public class User {

   @NotNull
   private String name;


   // ...
}
Value passedValidation result
<null>🍎 – validation failed
“”🍏 – validation passed
" "🍏 – validation passed
“Alex”🍏 – validation passed

Note: only null values are not allowed, emtpy value will pass this validation.

@NotEmpty

public class User {

   @NotEmpty
   private String name;


   // ...
}
Value passedValidation result
<null>🍎 – validation failed
“”🍎 – validation failed
" "🍏 – validation passed
“Alex”🍏 – validation passed

Note: null and empty size/length values are not allowed, values with multiple spaces will pass this validation.

@NotBlank

public class User {

   @NotBlank
   private String name;


   // ...
}
Value passedValidation result
<null>🍎 – validation failed
“”🍎 – validation failed
" "🍎 – validation failed
“Alex”🍏 – validation passed

Note: null values are not allowed and trimmed length must be greater than zero.

Title image by Matthias BΓΆckel from Pixabay

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.