Let's define a few validations on the Todo bean:
public class Todo {
private int id;
@NotNull
private String user;
@Size(min = 9, message = "Enter atleast 10 Characters.")
private String desc;
A couple of important points to note are as follows:
- @NotNull: Validates that the user field is not empty
- @Size(min = 9, message = "Enter atleast 10 Characters."): Checks whether the desc field has at least nine characters
There are a number of other annotations that can be used to validate beans. The following are some of the Bean Validation annotations:
- @AssertFalse, @AssertTrue: For Boolean elements. Checks the annotated element.
- @AssertFalse: Checks for false.
- @Assert: Checks for true.
- @Future: The annotated element must be a date in the future.
- @Past: The annotated element must be a date in the past.
- @Max: The annotated element must be a number whose value must be lower or equal to the specified maximum.
- @Min: The annotated element must be a number whose value must be higher or equal to the specified minimum.
- @NotNull: The annotated element cannot be null.
- @Pattern: The annotated {@code CharSequence} element must match the specified regular expression. The regular expression follows the Java regular expression conventions.
- @Size: The annotated element size must be within the specified boundaries.