Search code examples
javabean-validationhibernate-validator

Error message issue with validating multiple fields of a bean


I used group sequence to prevent two error messages displayed same time for email field when I set email as an empty string(""). If I don't use group sequence, it will display both "email is required" and "email format is wrong."

Then I got another problem after use group sequence. I set an empty string ("") on the amount field and set krchoigmail.com on the email field. It only display "amount is required" error message because of group sequence. I need to display "email format is wrong." error message as well. How do I achieve this? I searched many times, but didn't find an answer to this question. Please help.

@NotBlank(message = "{error.req.integer.amount}")
public String getAmount() {
    return amount;
}

@NotBlank(message = "{error.req.email}")
@Email(message = "{error.format.email}", groups = ValidInput.class)
public String getEmail() {
    return email;
}

Solution

  • @NotBlank and @Email both share "" as invalid value. You might consider adding some kind of conversion service which converts "" into Null and replace the @NotBlank constraint with @NotNull. Null doesn't trigger @Email, but triggers @NotNull only. Groups are not necessary in this scenario.

    Regarding your second question, a constraint is per default in the group javax.validation.groups.Default. You set your @Email constraint explicitly in the group ValidInput.class.