Using Constraint Annotations
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;
@Builder // lombok annotation
public class User {
@NotNull(message = "Name cannot be null")
private String name;
@AssertTrue
private boolean working;
@Size(min = 10, max = 200, message = "About Me must be between 10 and 200 characters")
private String aboutMe;
@Min(value = 18, message = "Age should not be less than 18")
@Max(value = 150, message = "Age should not be greater than 150")
private int age;
@Email(message = "Email should be valid")
private String email;
// standard setters and getters
}
Validating Beans/Objects
To validate a bean, we first need a Validator object, which is built using a ValidatorFactory
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Any violations of the constraints defined in the User object will be returned as a Set:
User user = User.builder().working(true).aboutMe("Its all about me!").age(50).build();
Set<ConstraintViolation<User>> violations = validator.validate(user);
By iterating over the violations, we can get all the violation messages using the getMessage method:
for (ConstraintViolation<User> violation : violations) {
log.error(violation.getMessage());
}
Annotations Work on Elements of a Collections and Optional
List<@NotBlank String> preferences;
public Optional<@Past LocalDate> getDateOfBirth() {
return Optional.of(dateOfBirth);
}
Annotations Available
- @NotNull validates that the annotated property value is not null.
- @AssertTrue validates that the annotated property value is true.
- @Size validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties.
- @Min validates that the annotated property has a value not smaller than the value attribute.
- @Max validates that the annotated property has a value no larger than the value attribute.
- @Email validates that the annotated property is a valid email address.
- @NotEmpty validates that the property is not null or empty; can be applied to String, Collection, Map or Array values.
- @NotBlank can be applied only to text values and validates that the property is not null or whitespace.
- @Positive and @PositiveOrZero apply to numeric values and validate that they are strictly positive, or positive including 0.
- @Negative and @NegativeOrZero apply to numeric values and validate that they are strictly negative, or negative including 0.
- @Past and @PastOrPresent validate that a date value is in the past or the past including the present; can be applied to date types including those added in Java 8.
- @Future and @FutureOrPresent validate that a date value is in the future, or in the future including the present.