Reputation: 5314
I have a basic custom validation setup as below:
@NotNullOrEmpty(message="{err.msg.required}", fieldName="Email")
@ValidEmail(message="{err.msg.validEmail}", fieldName="Email")
private String email;
However, if the email is empty, BOTH are triggered because of course, an empty email is not a valid email.
How do I trigger only @NotNullOrEmpty
if its empty and only trigger @ValidEmail
if it's non-empty?
Or is it possible to like
@Annotation1
@Annotation2 //trigger only if value has passed @Annotation1
What I have in mind is to edit my ValidEmailValidator.isValid()
to return true if email is empty, but what if I want to validate empty emails in the future?
Upvotes: 1
Views: 253
Reputation: 691745
The standard way, implemented by all the standard annotations, is to consider an email valid if it's null or empty. So if you have a required email, you annotated the field with NotEmpty and Email. If you have a non-required email, you just annotate it with Email.
For the reference, here are the first lines of code of the standard EmailValidator:
if ( value == null || value.length() == 0 ) {
return true;
}
Upvotes: 2