Home > Back-end >  Forcing validation annotation to provide a message
Forcing validation annotation to provide a message

Time:09-17

I am using hibernate validator to do POJO validation, and also i have created some custom ones. Here is an example:

//lombok annotations
public class Address {
  @NotNull // standard
  @State //Custom created
  String country;
}

We have a requirement to represents all the validations errors with specific codes rather than messages. In order to achieve this we have decided to specify codes in every annotation that we use. The above example now looks like this:

//lombok annotations
public class Address {
  @NotNull(message="ERR_001")
  @State(message="ERR_002")
  String country;
}

But we have a problem with this approach. We could not enforce to provide a message(error code in our case) all the time in an annotation. For custom annotation, it is still ok as we do not provide a default message, but for the standard ones there is chance to miss it and a string message will silently generated if we accidentally miss to provide a custom message.

Is there a way to enforce to provide message all the time in the annotation. It will probably help to have some consistency.

CodePudding user response:

To my knowledge no, there is no way to do that. Maybe your best option is to create your own annotation and make the attribute mandatory.

CodePudding user response:

Sevntu-Checkstyle provides additional checks to Checkstyle, including a check that an annotation is used with all required parameters.

<module name="RequiredParameterForAnnotation">
  <property name="annotationName" value="NotNull"/>
  <property name="requiredParameters" value="message"/>
</module>

CodePudding user response:

I could not find a good way to handle it. But for now i have implemented a test which give us some control over it. Its not the best solution but solves the issue for now.

I am using classgraph to read all the annotations on POJO classes inside a package and filtering it on javax validations and if the default messages appears to be from javax.validation, then i am adding to a list. Later on a unit test, i am checking if this list is empty or not.

private List<String> getAnnotationProperties(String appliedOn, AnnotationInfoList annotationInfos) {
    return annotationInfos.stream()
            .filter(annotationInfo -> annotationInfo.getName().contains("javax.validation.constraints"))
            .filter(annotationInfo -> ((String) annotationInfo.getParameterValues().getValue("message")).contains("javax.validation.constraints"))
            .map(annotationInfo -> annotationInfo.getName())
            .collect(Collectors.toList());
    }
  • Related