CustomerBirthdayValidator implements Validator { @Override public void validate(Object target, Errors errors) { CustomerForm customer = (CustomerForm) target; try { new DateTime(customer.getCustomerBirthYear(), customer .getCustomerBirthMonth(), customer .getCustomerBirthDay(), 0, 0).toDate(); } catch (IllegalArgumentException e) { errors.rejectValue("customerBirthYear", "IncorrectDate.customerBirth", "Incorrect date was entered."); } }  @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors);  }
@Test public void testValidate01() { CustomerBirthdayValidator validator = new CustomerBirthdayValidator(); CustomerForm customer = new CustomerForm(); customer.setCustomerBirthYear(2011); customer.setCustomerBirthMonth(2); customer.setCustomerBirthDay(28); BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm"); validator.validate(customer, result); assertThat(result.hasErrors(), is(false)); }
@Test public void testValidate02() { CustomerBirthdayValidator validator = new CustomerBirthdayValidator(); CustomerForm customer = new CustomerForm(); customer.setCustomerBirthYear(2011); customer.setCustomerBirthMonth(02); customer.setCustomerBirthDay(29); BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm"); validator.validate(customer, result); assertThat(result.hasErrors(), is(true)); FieldError error = result.getFieldError("customerBirthYear"); if (error != null) { assertThat(error.getCode(), is("IncorrectDate.customerBirth")); assertThat(error.getDefaultMessage(), is( "Incorrect date was entered.")); } else { fail("error"); } }
@Test public void testValidate03() { CustomerBirthdayValidator validator = new CustomerBirthdayValidator(); CustomerForm customer = new CustomerForm(); customer.setCustomerBirthYear(2012); customer.setCustomerBirthMonth(2); customer.setCustomerBirthDay(29); BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm"); validator.validate(customer, result); assertThat(result.hasErrors(), is(false)); }