简体   繁体   English

Spring Rest控制器中JSON验证中的强制属性注释

[英]Annotation for Mandatory attribute in json validation in spring rest controller

I have a spring rest service which accepts the Person object. 我有一个Spring Rest服务,它接受Person对象。 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 . 如果电话号码属性存在,它将使用@NotNull@NotBlank@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. 请提出建议的所有验证注释,以检查JSON请求中是否存在该属性。

following is the request body test cases 以下是请求正文测试用例

{"name":"anu", "phoneNumber": "","email" :"test@gmail.com" } // Validation works {“ name”:“ anu”,“ phoneNumber”:“”,“ email”:“ test@gmail.com”} //验证有效

{"name":"anu", "phoneNumber": null,"email" :"test@gmail.com" } // Validation works {“ name”:“ anu”,“ phoneNumber”:null,“ email”:“ test@gmail.com”} //验证有效

{"name":"anu","email" :"test@gmail.com" } // Validation doesnt works', Required help to find the annotation. {“ name”:“ anu”,“ email”:“ test@gmail.com”} //验证无效”,查找注释所需的帮助。

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. 我尝试了@ NotNull,@ Notempty,@ NotBlank。 Please help 请帮忙

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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