@NotBlank(message = "userCategory is missing")
@Pattern(regexp = "Single|Married", message = "userCategory is invalid")
private String userCategory;
Currently when validation happens, it gives me two error messages when I provide a whitespaces/blank value for userCategory.
"errors": [
{
"message": "userCategory is missing"
},
{
"message": "userCategory is invalid"
}
]
I want to throw a missing value if it's whitespace/blank and don't want the invalid error in case of empty value or whitespace. I want to say userCategory is invalid only when there is something typed invalid like abddd instead of Single or Married, something other than whitespaces/empty value with a invalid value.
I'm expecting an error message something like the below when userCategory is empty or when whitespace is typed.
"errors": [
{
"message": "userCategory is missing"
}]
@Pattern
will ignore anull
value but for blank values, I think your easiest option is to accept a blank value in your pattern.Another option would be to use a composing constraint where you disable the default messages and add your own (note the
@ReportAsSingleViolation
annotation). You don't have much flexibility for the message though:And the last option would be to implement your own validator. In this case, you have full flexibility about the validation process and the validation message.
Marko from the Hibernate team wrote a very complete blog post about it on the Hibernate blog: https://in.relation.to/2017/03/02/adding-custom-constraint-definitions-via-the-java-service-loader/ .