First of all, an emailId like lafalsdf@ga is valid as per RFC 822 (see here) because ga
is a valid local host name. Since most of the email validators follow RFC 822, they too consider it valid. This is the case for Hibernate Validator,Java's native InternetAddress.validate()
etc. However there is Apache Commons Validator project which provides an option to ignore local addresses when performing a validation.
If your concern is only with email validation, you don't have to look for a replacement for Hibernate Validator. You can write a custom annotation and validator which uses Apache commons validator as shown below.
@Constraint(validatedBy = CommonsEmailValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface CommonsEmail {
String message() default "{org.hibernate.validator.constraints.Email.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Defines several {@code @Email} annotations on the same element.
*/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface List {
CommonsEmail[] value();
}
public static class CommonsEmailValidator implements ConstraintValidator<CommonsEmail, CharSequence> {
@Override
public void initialize(CommonsEmail annotation) {
}
@Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
return EmailValidator.getInstance(false).isValid(value.toString());
}
}
}
Now, you can use new @CommonsEmail
instead of @Email
. EmailValidator
is part of commons validator library. So make sure commons-validator.jar is in your classpath.