Search code examples
spring-mvcbean-validationspring-restspring-validator

Spring Rest Validation using @Valid and @InitBinder together


I have a spring REST app and I want to make use of @Valid annotations to decorate the bean fields that can be validated for simple @NotNull checks.

public ResponseEntity<ExtAuthInquiryResponse> performExtAuthInq(@Valid @RequestBody ExtAuthInquiryRequest extAuthInquiryRequest)

like this

 @NotBlank(message = "requestUniqueId cannot be blank..")
private String requestUniqueId;

In addition to that I want to use @initBinder for doing more complex validations (like based on one field's value the second field is mandatory)

 @InitBinder("extAuthInquiryRequest")
protected void initExtAuthInqRequestBinder(WebDataBinder binder) {
    binder.setValidator(extAuthInqValidator);
}

Here's the validator implementation (only for conditional validation cases)

@Override
public void validate(Object target, Errors e) {

    ExtAuthInquiryRequest p = (ExtAuthInquiryRequest) target;
    // Dont want to do this check here. Can be simply done in the bean using @NotNull checks
    ValidationUtils.rejectIfEmpty(e, "requestUniqueId", "requestUniqueId is empty");


    // this is a good candidate to be validated here
    if(StringUtils.isNotBlank(p.getPersonInfo().getContactInfo().getPhoneNumber().getPhoneType())){
        if(StringUtils.isBlank(p.getPersonInfo().getContactInfo().getPhoneNumber().getPhoneNumber())){
            e.rejectValue("personInfo.contactInfo.phoneNumber.phoneNumber", "phoneNumber is mandatory when phoneType is provided");
        }
    }
}

}

I have seen a bunch of examples online which use either one or the other. I have tried doing both approaches together but when I have @initBinder setup, the @valid annotations on the request object are not honoured anymore.

Because I don't want to write code in a spring validator class for simple @NotNull checks. Is there a way to do both methods together.


Solution

  • found this link online spring bean validation delegating to JSR-303 for simple field level validation

    works like a charm..