javaspring-bootbean-validationjsr

Custom bean validation


I'm developing an application using spring-boot. I want to validate the user bean using JSR annotation. The problem is that I have some fields that depend on the value of others. For example when status="user_pr" I have to make the address, county, and phoneNumber as mandatory.

this my bean:

 @JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {

    @NotNull(message = "required")
    private String status;

    @JsonProperty("first_name")
    @NotNull(message = "required")
    private String firstName;

    @NotNull(message = "required")
    private String name;

    @NotNull(message = "required")
    @Pattern(message = "Email not valid", regexp = "^([\\w\\.\\-_]+)?\\w+@[\\w-_]+(\\.\\w+){1,}$")
    private String mailAddress;

    private String country;
    private String phoneNumber;

    @JsonProperty("address")
    private Address billingAddress;
}

Would you have any ideas ?

Best regards


Solution

  • I had the same problem a couple of weeks ago, I created my own validation annotation with a custom validation logic. You can find the showcase project in my repository: ConditionalValidator. If you have any questions, just ask.