0

I am using hibernate validators to implement validations in my application. I have also used custom annotations and custom validators for business validation requirements. It is working fine and I am able to get the specific error messages as per the implementation. But, now i also want to return error code (something like given in below code snippet) along with error message for each of the validations to the method where validate method is called.

I have read the documentation for hibernate validations but couldn't find anything for this requirement. Can some one please help me to implement error codes in this scenario.

@ValidStateInCountry(code=006, message="Invalid state for given country")
@ValidZipInCountry(code=007, message="Invalid zip for given country")
public class  Address {

@NotBlank(code=001, message="address line is mandatory")
private String addressLine;

@ValidCountry(code=002, message="Invalid Country name")
@NotBlank(code=003, message="Country name is mandatory")
private String country;

@NotBlank(code=004, message="state is mandatory")
private String state;

@NotBlank(code=005, message="zip is mandatory")
private String zipCode;

}
2
  • 1
    A good question. Have you tried this approach?: stackoverflow.com/a/2911486/3368818 Commented Sep 7, 2020 at 17:45
  • @J Woodchuck : Yes I have tried but it will not work in my case..i have multiple class level and property level custom validators and I need separate error codes for each validation failure. Commented Sep 7, 2020 at 17:51

1 Answer 1

0

First, we don't support that for the built-in constraints so you will have to reimplement them yourselves to add this feature.

Second, I think what you need is what we call a dynamic payload that you can attach to the ConstraintViolation when creating it in your ConstraintValidator. Then you can unwrap the violation to the Hibernate Validator-specific flavor of it and make use of it. See https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-dynamic-payload for a complete example.

You can extract the error code from the annotation once by implementing initialize(): https://github.com/eclipse-ee4j/beanvalidation-api/blob/2.0.2/src/main/java/javax/validation/ConstraintValidator.java#L50 .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.