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 {
 public void testForm() {
  Validator validator = Validation.buildDefaultValidatorFactory()

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

  Set<ConstraintViolation<Car>> constraintViolations = validator

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


class Car {

 private String manufacturer;

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

 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

There's good news for GWT users - bean validation is supported out-of-the-box in GWT 2.5.0+ . 


Popular posts from this blog

Complete guide to DTH setup

RO purifier maintenance

Watching Television on Computer using DVBSky S960