简体   繁体   中英

Json request validation for mandatory field - springboot rest-api

In below json request, you can see salary is available at 3 level student level, trainee level and properties level

employee{
id :"123";
name : "ABC";
salary : 100;
college : "abcd..";
Trainees : {
  id :"101";
  name :"XYZ";
  salary :50;
 }
properties :{ // key value pair values
  default.salary= 20
  default.college=null
 }
}  

As salary is mandatory for my application, so salary should be available at least one level.

If salary field and its value is not available at all level then some error should be thrown and request should not be processed by rest webservice and if salary is available at any one level then request should be accepted and processed by rest webservice.

I am using currently javax.validation.constraints for json request validation, Is there any way to achieve above requirement?

If you want to use javax bean validations you will need to define a custom annotation (there is not a default one for you specific use case) and implement ConstraintValidator with your custom validation. You can see examples here: https://www.baeldung.com/javax-validation-method-constraints .

In this case the 3 salary fields should be nullable and your validation logic should verify that at least one of them is not null.

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