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 passed | Validation 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 passed | Validation 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 passed | Validation 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