Home > Blockchain >  Spring @RequestBody validation issue using @Valid annotation
Spring @RequestBody validation issue using @Valid annotation

Time:10-22

I am trying to perform validation on Spring Boot @RequestBody JSON object using @Valid annotation.

This JSON object POJO class will contain another nested object. I have added field-level annotation for the nested object classes.

Also, I have added the @Valid annotation when adding the nested class object in the main object class.

But still, the validation for the nested class objects is not getting triggered when we are not passing the correct object.

Please find the code below for reference.

ExceptionController.class

@RestController
@RequestMapping("/student")
public class ExceptionController {
  
  @PostMapping
  @ResponseStatus(HttpStatus.CREATED)
  public String createStudent(@Valid @RequestBody Student student, HttpStatus status) {
    Student student1 = student;
    return "student data created!!";
  }
}

Student.class

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
  @NotEmpty(message = "First Name field can not be null or empty")
  @NotBlank(message = "First Name field can not be blank")
  private String firstName;
  @NotEmpty(message = "Last Name field can not be null or empty")
  @NotBlank(message = "Last Name field can not be blank")
  private String lastName;
  @Valid
  private Subject subject;      
}

Subject.class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Subject {
  @NotEmpty(message = "Topic field can not be null or empty")
  @NotBlank(message = "Topic field can not be blank")
  private String topic;
}

When I am not sending any data for Subject in the request it is not giving any exception and returns HTTP 200 OK status.

Any help will be highly appreciated.

CodePudding user response:

Try adding @NotNull annotation to Subject subject:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
  @NotEmpty(message = "First Name field can not be null or empty")
  @NotBlank(message = "First Name field can not be blank")
  private String firstName;
  @NotEmpty(message = "Last Name field can not be null or empty")
  @NotBlank(message = "Last Name field can not be blank")
  private String lastName;
  @Valid
  @NotNull
  private Subject subject;      
}

Your current validations would only work if you actually send Subject data but with an empty topic attribute.

On another topic, you might drop the @NotEmpty annotations because @NotBlank does not allow null or empty Strings.

  • Related