[Report As Single Violation] To prevent the custom validation from reinventing the wheel [Summary of existing annotations]

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

If multiple people are developing the API, the same items will appear in the API.

--Order number (orderNo) --Product code (itmCd) --Management number (mngNo) --User ID (usrId)

If it is the same item, it is natural to validate it with the same annotation. However, even if I tried hard to disseminate the documents and rules, I couldn't communicate with each other and the annotations were misaligned. ..

I think there is custom validation as one of the solutions in such a case.

Custom validation pattern

I think there are two main types.

--Things that require completely original logic --A level that can be combined with existing validation

** When creating the latter, did you build your own logic? ** **

We recommend that you consider using ** @ ReportAsSingleViolation **.

ReportAsSingleViolation In a word ** "Annotation that puts together annotations" **

I will describe the points after the source below.

@Constraint(validatedBy = {})
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@Size(min = 8, max = 10)
@Pattern(regexp = "^[a-zA-Z0-9]*$")
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 an existing combination, 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" The default message works when you use @ReportAsSingleViolation. This is amazing. At the time of validation operation, two messages of @ Size and @ Pattern are not output, only the message set by you 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 postpone applying it to the current project. .. Easy enough to destroy the stereotype.

However, the effect is strong. In the sample, I prevented the following from being scattered among multiple DTO classes and GET parameters that use the user ID field.

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

Please try it.

Recommended Posts

[Report As Single Violation] To prevent the custom validation from reinventing the wheel [Summary of existing annotations]
How to get the longest information from Twitter as of 12/12/2016