0

When i Try to validate email id using jersey the built in hibernate-validator is not validating it properly the fallowing string lafalsdf@ga get evaluatied to valid and it fallows JSR 303 which is old .I need library which validates according to JSR 311 & JSR 339 . Or any other library which is better than hibernate-validator

If there is any library please suggest me . I have done research and was not able to find any.

And also give me code to configure it in jersey

harsha kumar Reddy
  • 1,251
  • 1
  • 20
  • 32

1 Answers1

1

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.

Community
  • 1
  • 1
Justin Jose
  • 2,121
  • 1
  • 16
  • 15