简体   繁体   中英

Annotation for Mandatory attribute in json validation in spring rest controller

I have a spring rest service which accepts the Person object. Person object has a name, phone number, and email. While adding a person, the phone number is mandatory. If the phone number attribute is present, it validates for null or empties using @NotNull or @NotBlank or @NotEmpty . But if the attribute doesn't exist, the validation is not working. Please suggest any validation annotation present to check the attribute exists in JSON request.

following is the request body test cases

{"name":"anu", "phoneNumber": "","email" :"test@gmail.com" } // Validation works

{"name":"anu", "phoneNumber": null,"email" :"test@gmail.com" } // Validation works

{"name":"anu","email" :"test@gmail.com" } // Validation doesnt works', Required help to find the annotation.

class Person {
 @NotNull
private String name;
  @NotNull(message = "email.empty") 
   @Email(regexp = EMAIL_PATTERN, message = "email.invalid")
private String email;
 @NotNull(message = "phonenumber.empty")
   @Pattern(regexp = PHONE_NUMBER_PATTERN, message = "phonenumber.invalid")
private String phoneNumber;
...
}

Please find my controler

@RequestMapping(value = "/createAdminPerson", method = POST, consumes = BusinessPersonConstants.MEDIA_TYPE, produces = "application/json;charset=UTF-8")
    public ResponseEntity<Boolean> createAdminPerson(
            @Validated @RequestBody Person createAdminPerson) {
...
}

I tried @NotNull, @Notempty, @NotBlank. Please help

在控制器中,我使用@Validated来验证请求主体,当我尝试@Valid时,验证工作正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM