Bean Validation

  • Almost all validations constraint annotation specification comes from javax.validation.constraints.

  • Bean Validation is a standard validation specification, that allows to validate domain objects.

  • One of the validation provider of this specification is hibernate-validator.

Validator specified in javax

  • To check if an email is valid use, @Email.

  • To check if a collection or string is not empty use, @NotEmpty

  • To check if a reference type is not NULL use, @NotNull.

  • To check if a string is a valid sequence of characters, use @Pattern. For eg,

    	@Pattern(regexp="((?=.*\\d)(?=.*[a-z])(?=.*[#@$*]).{5,20})")
    	String pattern

Hibernate specific validators

  • These annotations are provided by hibernate validator org.hibernate.validator.constraint

    • To restrict length of string use @Length(min=5, max=10), this annotation is hibernate specific

    • To check if a specific numeric or string form of numeric value is within the given range use @Range(min=200, max=2000)

Springframework

  • These annotation are provided by spring framework from org.springframework.format.annotation.

    • @DateTimeFormat annotation is used to specify formatting style of date/time data types. This annotation can only be applied to java.util.date,java.util.Calendar, Long or java.time.* types.

    	@DateTimeFormat(pattern="dd-MMM-yyyy")
    	private Date regDate;
Bean Validation Diagram

Last updated