Spring Validation Tutorial for Java beginners

Spring Validation is the combination of Validator interface and DataBinder or in other words spring achieve validation with the help of these two. Validator interface can be used  to validate an Object, which(validator interface) in turn uses Error Object to report any validator error while validating an Object.

Validator(org.springframework.validation.Validator) interface has two main methods.

  1. supports(Class)  : Class(Instance of) this validator supports to.
  2. validate(Object, org.springframework.validation.Errors) : Validate the Object and reports the validation error via Error Object

 Example

 

How to Re-Use Validator

There might be the case when Object in application has the reference of another Object. Like Person object has an Address property which is in itself an Object. So instead of writing(Copy and paste from Address validator) validator code for Contact you can dependency inject Address validator in Contact validator.

Example

 

Leave A Comment

Your email address will not be published. Required fields are marked *