HibernateValidatorProperty implements IValidator<Object> { public void validate(IValidatable<Object> validatable) { Validator validator = HibernateValidatorProperty.validatorFactory.getValidator(); @SuppressWarnings("unchecked") Set<ConstraintViolation<Object>> violations = validator.validateValue((Class<Object>)beanModel.getObject().getClass(), propertyName, validatable.getValue()); if(!violations.isEmpty()){ for(ConstraintViolation<?> violation : violations){ ValidationError error = new ValidationError(violation.getMessage()); String key = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(); if(getValidatorPrefix()!=null) key = getValidatorPrefix()+"."+key; error.addKey(key); error.setVariables(new HashMap<String, Object>(violation.getConstraintDescriptor().getAttributes())); error.getVariables().remove("payload"); error.getVariables().remove("message"); error.getVariables().remove("groups"); validatable.error(error); } } } HibernateValidatorProperty(IModel<?> beanModel, String propertyName); void validate(IValidatable<Object> validatable); static final ValidatorFactory validatorFactory; }
@Test public void testNotNull() { IValidator<Object> validator = new HibernateValidatorProperty(new Model<TestBean>(new TestBean("aaa", "aaa")), "a"); Validatable<Object> validatable = new Validatable<Object>(null); validator.validate(validatable); assertEquals(1, validatable.getErrors().size()); assertEquals("NotNull", getError(validatable).getKeys().get(0)); }
@Test public void testSuccess(){ IValidator<Object> validator = new HibernateValidatorProperty(new Model<TestBean>(new TestBean("aaa", "aaa")), "a"); Validatable<Object> validatable = new Validatable<Object>("bb"); validator.validate(validatable); assertEquals(0, validatable.getErrors().size()); }
@Test public void testMessageParameters(){ IValidator<Object> validator = new HibernateValidatorProperty(new Model<TestBean>(new TestBean("aaa", "aaa")), "b"); Validatable<Object> validatable = new Validatable<Object>("a"); validator.validate(validatable); assertEquals(1, validatable.getErrors().size()); assertEquals("Size", getError(validatable).getKeys().get(0)); assertEquals(2, getError(validatable).getVariables().size()); assertEquals(2, getError(validatable).getVariables().get("min")); assertEquals(4, getError(validatable).getVariables().get("max")); }