Domanda

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;
}
È stato utile?

Soluzione

@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.

Altri suggerimenti

Markus: Thanks for getting back to me. I have to use this Answer field since I don't have 50 reputation to write relatively comment. Indeed @NotNull didn't trigger @Email. I resolved my issue by writing custom validations, but I like your answers better than custom validation. Could you give me some details about why @NotBlank triggers @Email while @NotNull is not? It seems that this behavior makes @NotBlank less useful. I used your suggestion and it worked. I didn't need a group. Thank you.

@NotNull(message = "{error.req.email}")
@Email(message = "{error.format.email}")
public String getEmail() {
    return email;
}

public void setEmail(String email) {
    if ((email != null) && email.trim().isEmpty()) {
        email = null;
    } else {
        this.email = email;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top