Bean validation

Bean validation, validating the properties of a Java bean, is the most oft used pattern in any application. In the past, people have been creating their own frameworks to handle the same. JSR-309/JSR-349 strives to create a standardized way of addressing this issue. Below is an example of simplicity and elegance of this solution.

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * @author Anand.Tamariya
 * 
 */
public class TestValidation {
 @Test
 public void testForm() {
  Validator validator = Validation.buildDefaultValidatorFactory()
    .getValidator();

  Car car = new Car(null, "DD-AB-123", 4);

  Set<ConstraintViolation<Car>> constraintViolations = validator
    .validate(car);

  assertEquals(1, constraintViolations.size());
  assertEquals("may not be null", constraintViolations.iterator().next()
    .getMessage());
 }

}

class Car {

 @NotNull
 private String manufacturer;

 @NotNull
 @Size(min = 2, max = 14)
 private String licensePlate;

 @Min(2)
 private int seatCount;

 public Car(String manufacturer, String licencePlate, int seatCount) {
  this.manufacturer = manufacturer;
  this.licensePlate = licencePlate;
  this.seatCount = seatCount;
 }

 // getters and setters ...
}
Find out more at http://hibernate.org/validator/documentation/getting-started/

There's good news for GWT users - bean validation is supported out-of-the-box in GWT 2.5.0+ http://www.gwtproject.org/doc/latest/DevGuideValidation.html . 

Comments

Popular posts from this blog

GNU Emacs as a Comic Book Reader

Mozilla Readability in GNU Emacs

Data Visualization with GNU Emacs