@NotNull(message = "emailAddress is mandatory")
@NotEmpty(message = "emailAddress cannot be empty")
@Email(message = "Invalid Email")
private String emailAddress;
I just want to know from outside , emailAdress has Email annotation. Is there any way that we can say it is an email annotaion?
CodePudding user response:
You can use reflection for this. The following test passes:
public class MyTest {
@Test
public void test() throws NoSuchFieldException {
HasEmailAddressValidator hasEmailAddressValidator = new HasEmailAddressValidator();
boolean result = hasEmailAddressValidator.hasEmailAddress(MyClass.class);
assertTrue(result);
}
@NoArgsConstructor
static
class HasEmailAddressValidator {
public boolean hasEmailAddress(Class<?> clazz) throws NoSuchFieldException {
return clazz.getDeclaredField("email").isAnnotationPresent(Email.class);
}
}
@Data
static
class MyClass {
@Email(message = "this is an email address")
private String email;
}
}
CodePudding user response:
Create your custome Annotation.
`import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = EmailValidator.class)
@Documented
public @interface ValidEmail {
String message() default "Invalid Email";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
// Email Validator
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\ ] (\\.[_A-Za-z0-9-] )*@" "[A-Za-z0-9-] (\\.[A-Za-z0-9] )*(\\.[A-Za-z]{2,})$";
private static final Pattern PATTERN = Pattern.compile(EMAIL_PATTERN);
@Override
public boolean isValid(final String username, final ConstraintValidatorContext context) {
return (validateEmail(username));
}
private boolean validateEmail(final String email) {
Matcher matcher = PATTERN.matcher(email);
return matcher.matches();
}
}
// Now in your DTO and Model
@ValidEmail
@NotNull
@Size(min = 1, message = "Invalid Email")
private String email;