Wednesday, January 7, 2015

Validation

Every web site should have validation for client and server site. Simple validation by client site I describe in previous post, here I'll create server validation. At first I added to pom.xml file dependency:

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>

Next in domain file adding annotation to the fields in object like:
- @NotNull
- @Size
- @MaxSize
- @MinSize
- @Unique
- @Email

All of the validations used above are part of the JSR-303 API, except for “NotEmpty” and “Email”, which are Hibernate-Validator annotations.
Next in controller file adding to method @Valid annotation and BindingResult

Simply adding annotation @Valid tells Spring to validate the “Person” object.  I also add a BindingResult argument. BindingREsult is Spring’s object which holds the result of the validation, binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.

When Spring sees @Valid, it tries to find the validator for the object being validated. Spring automatically picks up validation annotations if you have “annotation-driven” enabled. Spring then invokes the validator and puts any errors in the BindingResult and adds the BindingResult to the view model.

No comments:

Post a Comment