I want to create custom email validator using annotations. This solution was useful while creating the validator. Here's the annotation :
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {CommonsEmailValidator.class})
@Documented
@ReportAsSingleViolation
public @interface ExEmailValidator {
String message() default " {org.hibernate.validator.constraints.Email.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface List {
ExEmailValidator[] value();
}
}
And here's the class CommonsEmailValidator :
public class CommonsEmailValidator implements ConstraintValidator<ExEmailValidator, String> {
private static final boolean ALLOW_LOCAL = false;
private EmailValidator realValidator = EmailValidator.getInstance(ALLOW_LOCAL);
@Override
public void initialize(ExEmailValidator email) {
// TODO Auto-generated method stub
}
@Override
public boolean isValid(String email, ConstraintValidatorContext constraintValidatorContext) {
if( email == null ) return true;
return realValidator.isValid(email);
}
}
I run the project, but, when I click submit on the registration form, while the email format is not valid I have the following exception :
Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [...] during persist time for groups [javax.validation.groups.Default, ]
the exception was as excpected, But instead of showing a 500 error, I would like to see an error message explaning what's wrong. So, I think I have to use ConstraintValidatorContext to define custom error messages. But, I don't know how to do it. Any ideas please ?