sharpcodes
sharpcodes

Reputation: 143

spring boot request validations not working

Application background

Problem

The swagger templates created using open API 3.0 were converted to pojos using swagger-codegen-maven-plugin..

Here is the generate pojo

public class TestPojo {

  @JsonProperty("isNameValid")
   private Boolean isNameValid = null;

 @Schema(
    required = true,
    description = "Checks if name is Valid "
)
public Boolean isIsNameValid() {
    return this.isNameValid;
}

}

Here is the swagger template used

openapi: 3.0.1
info:
title: XM MNOLine Domain Definitions
description: |
version: "V0.0.1"

components:
 schemas:

  TestPojo:
      required:
        - isNameValid
      properties:
        isNameValid:
          type: boolean
          description: |
            Checks if name is Valid

In the controller the @Valid annotations don't seem to have any impact..Null or no values for the field "isNameValid" is still processed..

 processRequest(@Valid @RequestBody TestPojo request)

What am I missing ..

Upvotes: 1

Views: 4763

Answers (2)

semicolon
semicolon

Reputation: 545

if I'm understanding it correct then you want your "isNameValid" field to be present in request else throw exception.

So, in order to make your field mandatory in request you will have to annotate it with @NotNull.

ex.

    public class TestPojo {

         @JsonProperty("isNameValid")
         @NotNull
         private Boolean isNameValid;

         public void setIsNameValid(Boolean isNameValid) {
             this.isNameValid = isNameValid;
         }

         public Boolean isNameValid() {
             return isNameValid;
         }

    }

Above code will not allow null values for that field i.e. request will need to have isNameValid .

I hope it solves your problem.

If I have misunderstood your requirement, let me know and will try to solve your problem.

EDIT

Hi, I currently don't have any ongoing project with swagger open api use, so I can't test it, but can you check Validate spring contracts .

I hope this can be helpful, else let me know.

Good luck!

Upvotes: 0

sharpcodes
sharpcodes

Reputation: 143

Looks like this issue is already reported .. https://github.com/swagger-api/swagger-codegen/issues/7058

Upvotes: 1

Related Questions