ModelValidator { public List<ValidationError> getUpdateValidationErrors(Update<?> update, FieldData fieldData) { if (update == null) { return ImmutableList.of(ValidationError.of("", "update is null")); } ImmutableList.Builder<ValidationError> errors = ImmutableList.builder(); Set<String> updateFields = update.getUpdateFields(); for (String fieldName : updateFields) { Field field = fieldData.getMap().get(fieldName); if (field == null) { errors.add(ValidationError.of(fieldName, "does not exist")); } else if (!field.isUpdatable()) { errors.add(ValidationError.of(fieldName, "is not updatable")); } else if (!field.isOptional() && update.getRemoveFields().contains(fieldName)) { errors.add(ValidationError.of(fieldName, "is required")); } } Set<ConstraintViolation<Object>> violations = validator.validate(update.getPartial(), Default.class); Set<String> errorFields = new HashSet<>(); for (ConstraintViolation<?> cv : violations) { String field = cv.getPropertyPath().toString(); if (updateFields.contains(field) && !errorFields.contains(field)) { errors.add(ValidationError.of(field, cv.getMessage())); errorFields.add(field); } } return errors.build(); } ModelValidator(Validator validator, ObjectMapper mapper); List<ValidationError> getModelValidationErrors(Object object, Class validationGroup); List<ValidationError> getCreateValidationErrors(Object create, FieldData fieldData); List<ValidationError> getUpdateValidationErrors(Update<?> update, FieldData fieldData); boolean validateModel(Object model); boolean validateCreate(Object create, FieldData fieldData); boolean validateUpdate(Update<?> update, FieldData fieldData);  }
@Test public void testGetUpdateValidationErrors() throws Exception { List<ValidationError> errors = validator.getUpdateValidationErrors(null, fieldData); assertEquals(1, errors.size()); Update<TestValidateModel> update = JsonHelper.update("{email:'bad'}", TestValidateModel.class); errors = validator.getUpdateValidationErrors(update, fieldData); assertEquals(1, errors.size()); assertEquals("must be a well-formed email address", errors.get(0).getMessage()); update = JsonHelper.update("{type:'change'}", TestValidateModel.class); errors = validator.getUpdateValidationErrors(update, fieldData); assertEquals(1, errors.size()); assertEquals("is not updatable", errors.get(0).getMessage()); update = JsonHelper.update("{email:null}", TestValidateModel.class); errors = validator.getUpdateValidationErrors(update, fieldData); assertEquals(1, errors.size()); assertEquals("email: is required", errors.get(0).toString()); }