How use Valid and NotBlank for swagger object?

Viewed 527

In my project I have a controller and dto which the same controller accepts. It was decided to use swagger-codegen as more appropriate. And then there were questions with validation, which I applied to my dto, but I can't apply to the object that swagger creates.

@Data
public class MyCustomDto {
    @NotBlank(message = ".... ")
    private String a;
    @NotBlank(message = ".... ")
    private String b;
}

Using MyCustomDto with @Valid annotation in the controller, I could validate the data and the request would not work if one of these fields is empty.

@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2021-05-23T15:23:40.775555+04:00[Asia/Baku]")
public class MySwaggerDto{
  @JsonProperty("a")
  private String a= null;

  @JsonProperty("b")
  private String b= null;
}

my yaml file part for those fields

        a:
          type: string
          description: sfdsfsdfdsf
          example: hh
        b:
          type: string
          description: asdsadas
          example: kjhgjgj

Can swaggerdto be made to work similarly to custom dto? I have a @ControllerAdvice class with a handleMethodArgumentNotValid method that I use to respond to a request with incorrect input parameters.

@ControllerAdvice
@Slf4j
public class MyExceptionsHandler extends ResponseEntityExceptionHandler {

   @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
            HttpHeaders headers, HttpStatus status, WebRequest request) {
//my some code
        return ResponseEntityBuilder.build(err);
    }
}
0 Answers
Related