# 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,

    ```java
    	@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.

    ```java
    	@DateTimeFormat(pattern="dd-MMM-yyyy")
    	private Date regDate;
    ```

![Bean Validation Diagram](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-10cbecac6d5c2f833377966e96b01c6ed48f1431%2Fvalidations.png?alt=media)
