[Java] [ReportAsSingleViolation] In order to avoid reinventing the wheel with that custom validation [Collect existing annotations]

1 minute read

Why do you want to create your own validation with Spring Boot?

The same item will appear in the API if multiple people are developing the API.

  • Order number (orderNo)
  • Product code (itmCd)
  • Control number (mngNo)
  • User ID (usrId)
  • And so on…

If it is the same item, it is natural to validate with the same annotation. However, even though I tried to make the documents and rules well known, I could not communicate well and the annotations were misaligned. ..

I think that one of the solutions at that time is custom validation.

Custom validation pattern

I think there are roughly two.

  • Things that require completely original logic
  • At a level that requires a combination of existing validations

**Are you creating your own logic when creating the latter? **

We recommend that you consider using @ReportAsSingleViolation**.

ReportAsSingleViolation

In a nutshell “Annotations that combine annotations”

I will describe the points after the source below.

@Documented
@Constraint(validatedBy = {})
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Size(min = 8, max = 10)
@Pattern(regexp = "^[a-zA-Z0-9]*$")
@ReportAsSingleViolation
public @interface UsrId {

    /** Error message when an error occurs */
    String message() default "User ID is not set correctly";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

Constraint(validatedBy = {})

It’s {}. If what you want to do is completed with existing combinations, you don’t need a validator class to write the logic. ** In fact, this custom annotation is just a combination of annotations.

message() default “xxx”

If you use @ReportAsSingleViolation, the default message will work. This is amazing. During validation operation, the two messages of @Size and @Pattern are not output, only the message set by me is output. ** In other words, the annotations are organized. **

at the end

If you create @ReportAsSingleViolation, custom validation is completed with one file.

I’m busy because custom validation seems difficult, so I’ll put it off for the current project. .. It’s as easy as destroying the stereotype.

However, the effect is strong. The sample prevented the following from being scattered across multiple DTO classes and GET parameters that use a user ID item.

  • @Size(min = 8, max = 10)
  • @Pattern(regexp = "^[a-zA-Z0-9]*$")

Use @UsrId as a rule! That is necessary. However, please make sure to use validation with specific arguments. I think that it is better than the rule.

Please try it.