Search code examples
javaspring-bootjavax.validation

Javax Validation is not stable if two or more annotation satisfies the condition on same field


I have observed one issue when I have applied the two validation annotations and both are checking the same conditions in some particular scenario, javax validation output is not stable. Here is the code example:

@NotBlank(message = "Date Missing")
@ValidDate(message = "Invalid Date")
private String date;

In the above code ValidDate is a custom Annotation which is checking if the given date is valid along with not null and NotBlank checks null, non empty.

so in case when date is null both are returning true and the message response is toggling between Date Missing and Invalid Date

Is there any way that I can stop this toggling and can use NotBlank only for the null case?


Solution

  • The reason for this is because order is not guaranteed by default for the execution of javax validations. Therefore, whatever gets executed first throws the error. use @GroupSequence for ordering

    An alternative would be to check for Not Blank as well and throw an appropriate error in your custom annotation ValidDate and remove the @NotBlank annotation from the property.