Java Validating a extended Pojo

925 Views Asked by At

I am building project on spring boot and want to add validation that are easy to integrate. I have Pojo for my project as below:

public class Employee{ 
    @JsonProperty("employeeInfo")
    private EmployeeInfo employeeInfo;
}

EmployeeInfo class is as below:

public class EmployeeInfo extends Info {
    @JsonProperty("empName")
    private String employeeName;
}

Info class is as below:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Info {
    @JsonProperty("requestId")
    protected String requestId;
}

How to I validate if request Id is not blank with javax.validation

My controller class is as below:

@RequestMapping(value = "/employee/getinfo", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<> getEmployee(@RequestBody Employee employee) {
    //need to validate input request here
    //for e.g to check if requestId is not blank
}

Request :

{
  "employeeInfo": {
    "requestId": "",
  }
}
2

There are 2 best solutions below

0
piy26 On

Considering you are making use of validation-api:

Please try using below to validate if your String is not null or not containing any whitespace

@NotBlank

0
Afridi On

In order to validate request parameters in controller methods, you can either use builtin validators or custom one(where you can add any type of validations with custom messages.)

Details on how to use custom validations in spring controller, Check how to validate request parameters with validator like given below:

@Component
public class YourValidator implements Validator {

@Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(Employee.class);
}

@Override
    public void validate(Object target, Errors errors) {
        if (target instanceof Employee) {
           Employee req = (Employee) target;
           ValidationUtils.rejectIfEmptyOrWhitespace(errors, "employeeInfo.requestId", "YourCustomErrorCode", "yourCustomErrorMessage");

           //Or above validation can also be done as
           if(req.getEmployeeInfo().getRequestId == null){
               errors.rejectValue("employeeInfo.requestId", "YourCustomErrorCode", "YourCustomErrorMessage");
           }
        }
    }
}