Hibernate validator: @Email accepts ask@stackoverflow as valid?












47















I'm using the @Email annotation to validate an e-mail address.
The issue I'm having is that it's accepting things like ask@stackoverflow as a valid e-mail address.
I guess this is because they want to support intranet addresses, but I can't seem to find a flag so it does check for an extension.



Do I really need to switch to @Pattern (and any recommendations for an e-mail pattern that's flexible) or am I missing something?










share|improve this question

























  • Are you referring to org.hibernate.validator.Email?

    – skaffman
    Dec 16 '10 at 10:06






  • 2





    org.hibernate.validator.constraints.Email; and version 4.0.2.GA

    – jack
    Dec 16 '10 at 10:12






  • 2





    An email without a dot in the domain is actually valid: isemail.info/about

    – OrangeDog
    Mar 22 '16 at 11:03






  • 1





    Please, don't use regexp validation for e-mails, just check if there's an @ inside and try to send an activation e-mail there. The only real validation we need is whether someone interested in our service can click on the attached link or not.

    – Artur Czajka
    Aug 18 '17 at 12:50








  • 1





    @chrylis Thanks for your contribution. Yes, you are right. In my system it would be expected as an invalid e-mail and therefore, rejected.

    – Val Martinez
    Apr 26 '18 at 15:59
















47















I'm using the @Email annotation to validate an e-mail address.
The issue I'm having is that it's accepting things like ask@stackoverflow as a valid e-mail address.
I guess this is because they want to support intranet addresses, but I can't seem to find a flag so it does check for an extension.



Do I really need to switch to @Pattern (and any recommendations for an e-mail pattern that's flexible) or am I missing something?










share|improve this question

























  • Are you referring to org.hibernate.validator.Email?

    – skaffman
    Dec 16 '10 at 10:06






  • 2





    org.hibernate.validator.constraints.Email; and version 4.0.2.GA

    – jack
    Dec 16 '10 at 10:12






  • 2





    An email without a dot in the domain is actually valid: isemail.info/about

    – OrangeDog
    Mar 22 '16 at 11:03






  • 1





    Please, don't use regexp validation for e-mails, just check if there's an @ inside and try to send an activation e-mail there. The only real validation we need is whether someone interested in our service can click on the attached link or not.

    – Artur Czajka
    Aug 18 '17 at 12:50








  • 1





    @chrylis Thanks for your contribution. Yes, you are right. In my system it would be expected as an invalid e-mail and therefore, rejected.

    – Val Martinez
    Apr 26 '18 at 15:59














47












47








47


20






I'm using the @Email annotation to validate an e-mail address.
The issue I'm having is that it's accepting things like ask@stackoverflow as a valid e-mail address.
I guess this is because they want to support intranet addresses, but I can't seem to find a flag so it does check for an extension.



Do I really need to switch to @Pattern (and any recommendations for an e-mail pattern that's flexible) or am I missing something?










share|improve this question
















I'm using the @Email annotation to validate an e-mail address.
The issue I'm having is that it's accepting things like ask@stackoverflow as a valid e-mail address.
I guess this is because they want to support intranet addresses, but I can't seem to find a flag so it does check for an extension.



Do I really need to switch to @Pattern (and any recommendations for an e-mail pattern that's flexible) or am I missing something?







hibernate validation spring-mvc hibernate-validator






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 13 '17 at 7:07









Andrii Abramov

4,17643047




4,17643047










asked Dec 16 '10 at 10:01









jackjack

97742540




97742540













  • Are you referring to org.hibernate.validator.Email?

    – skaffman
    Dec 16 '10 at 10:06






  • 2





    org.hibernate.validator.constraints.Email; and version 4.0.2.GA

    – jack
    Dec 16 '10 at 10:12






  • 2





    An email without a dot in the domain is actually valid: isemail.info/about

    – OrangeDog
    Mar 22 '16 at 11:03






  • 1





    Please, don't use regexp validation for e-mails, just check if there's an @ inside and try to send an activation e-mail there. The only real validation we need is whether someone interested in our service can click on the attached link or not.

    – Artur Czajka
    Aug 18 '17 at 12:50








  • 1





    @chrylis Thanks for your contribution. Yes, you are right. In my system it would be expected as an invalid e-mail and therefore, rejected.

    – Val Martinez
    Apr 26 '18 at 15:59



















  • Are you referring to org.hibernate.validator.Email?

    – skaffman
    Dec 16 '10 at 10:06






  • 2





    org.hibernate.validator.constraints.Email; and version 4.0.2.GA

    – jack
    Dec 16 '10 at 10:12






  • 2





    An email without a dot in the domain is actually valid: isemail.info/about

    – OrangeDog
    Mar 22 '16 at 11:03






  • 1





    Please, don't use regexp validation for e-mails, just check if there's an @ inside and try to send an activation e-mail there. The only real validation we need is whether someone interested in our service can click on the attached link or not.

    – Artur Czajka
    Aug 18 '17 at 12:50








  • 1





    @chrylis Thanks for your contribution. Yes, you are right. In my system it would be expected as an invalid e-mail and therefore, rejected.

    – Val Martinez
    Apr 26 '18 at 15:59

















Are you referring to org.hibernate.validator.Email?

– skaffman
Dec 16 '10 at 10:06





Are you referring to org.hibernate.validator.Email?

– skaffman
Dec 16 '10 at 10:06




2




2





org.hibernate.validator.constraints.Email; and version 4.0.2.GA

– jack
Dec 16 '10 at 10:12





org.hibernate.validator.constraints.Email; and version 4.0.2.GA

– jack
Dec 16 '10 at 10:12




2




2





An email without a dot in the domain is actually valid: isemail.info/about

– OrangeDog
Mar 22 '16 at 11:03





An email without a dot in the domain is actually valid: isemail.info/about

– OrangeDog
Mar 22 '16 at 11:03




1




1





Please, don't use regexp validation for e-mails, just check if there's an @ inside and try to send an activation e-mail there. The only real validation we need is whether someone interested in our service can click on the attached link or not.

– Artur Czajka
Aug 18 '17 at 12:50







Please, don't use regexp validation for e-mails, just check if there's an @ inside and try to send an activation e-mail there. The only real validation we need is whether someone interested in our service can click on the attached link or not.

– Artur Czajka
Aug 18 '17 at 12:50






1




1





@chrylis Thanks for your contribution. Yes, you are right. In my system it would be expected as an invalid e-mail and therefore, rejected.

– Val Martinez
Apr 26 '18 at 15:59





@chrylis Thanks for your contribution. Yes, you are right. In my system it would be expected as an invalid e-mail and therefore, rejected.

– Val Martinez
Apr 26 '18 at 15:59












8 Answers
8






active

oldest

votes


















33














Actually, @Email from Hibernate Validator uses regexp internally. You can easily define your own constraint based on that regexp, modified as you need (note the + at the end of DOMAIN):



@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@Pattern(regexp = Constants.PATTERN, flags = Pattern.Flag.CASE_INSENSITIVE)
public @interface EmailWithTld {
String message() default "Wrong email";
Class<?> groups() default { };
Class<? extends Payload> payload() default { };
}

interface Constants {
static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
static final String DOMAIN = "(" + ATOM + "+(\." + ATOM + "+)+";
static final String IP_DOMAIN = "\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]";

static final String PATTERN =
"^" + ATOM + "+(\." + ATOM + "+)*@"
+ DOMAIN
+ "|"
+ IP_DOMAIN
+ ")$";
}





share|improve this answer





















  • 17





    True, but I'm a bit surprised that I will need to make a custom validator for what seems like a really common requirement. I'd expect a flag for this kind of thing.

    – jack
    Dec 16 '10 at 15:25











  • A good way to customize some tips and tricks +1 :)

    – ThierryB
    May 22 '13 at 7:36






  • 1





    @Matt solution is much simpler as it only add one line in the annotations

    – Adrien Be
    Oct 1 '13 at 10:24











  • link in this answer is broken.

    – ruruskyi
    Nov 14 '17 at 9:55



















45














You can also use constraint composition as a work-around. In the example below, I rely on the @Email validator to do the main validation, and add a @Pattern validator to make sure the address is in the form of x@y.z (I don't recommend using just the @Pattern below for regular Email validation)



@Email(message="Please provide a valid email address")
@Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface ExtendedEmailValidator {
String message() default "Please provide a valid email address";
Class<?> groups() default {};
Class<? extends Payload> payload() default {};
}





share|improve this answer





















  • 1





    This is indeed the better solution

    – Arefe
    Sep 8 '17 at 6:00



















13














Actually validating e-mail addresses is really complex. It is not possible to validate that an e-mail address is both syntactically correct and addresses the intended recipient in an annotation. The @Email annotation is a useful minimal check that doesn't suffer from the problem of false negatives.



The next step in validation should be sending an e-mail with a challenge that the user has to complete to establish that the user has access to the e-mail address.



It is better to be accept a few false positives in step 1 and allow some invalid e-mail addresses to pass through than to reject valid users. If you want to apply additional rules you can add more checks, but be really careful about what you assume to be a requirement of a valid e-mail address. For instance there is nothing in the RFCs that dictates that i@nl would be invalid, because nl is a registered country top-level domain.






share|improve this answer





















  • 1





    This is the right answer!

    – Artur Czajka
    Aug 18 '17 at 12:54



















3














Here's a javax.validation email validator using Apache Commons Validator



public class CommonsEmailValidator implements ConstraintValidator<Email, String> {

private static final boolean ALLOW_LOCAL = false;
private EmailValidator realValidator = EmailValidator.getInstance(ALLOW_LOCAL);

@Override
public void initialize(Email email) {

}

@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if( s == null ) return true;
return realValidator.isValid(s);
}
}


And 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 Email {

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 {
Email value();
}
}





share|improve this answer































    0














    The constraint composition solution does not work. When Email is used in conjunction with Pattern, the Email regex is held in higher precedence. I believe this is because the Email annotation overrides a few Pattern attributes, namely flags and regexp (the key one here) If I remove @Email, only then will the @Pattern regular expression apply in validations.



    /**
    * @return an additional regular expression the annotated string must match. The default is any string ('.*')
    */
    @OverridesAttribute(constraint = Pattern.class, name = "regexp") String regexp() default ".*";

    /**
    * @return used in combination with {@link #regexp()} in order to specify a regular expression option
    */
    @OverridesAttribute(constraint = Pattern.class, name = "flags") Pattern.Flag flags() default { };





    share|improve this answer

































      0














      Obviously I am late to the Party, Still I am replying to this question,



      Why cant we use @Pattern annotation with regular expressions in our Validation class like this



      public Class Sigunup {

      @NotNull
      @NotEmpty
      @Pattern((regexp="[A-Za-z0-9._%-+]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")
      private String email;

      }


      Its easier.






      share|improve this answer


























      • ... and wrong. "test@myexample..loc" is valid with this regex.

        – Bertl
        Aug 8 '17 at 8:47











      • Can you please elaborate little more ?

        – user2245151
        Aug 9 '17 at 9:39











      • Double-Dots in the domain part are not recognized as wrong. Also, umlaut domains and many more valid email address patterns are not detected as valid. Therefore, it is better to let the validation be performed by special libraries, like Apache Commons EmailValidator. See gist.github.com/robertoschwald/ce23c8c23ebd5b93fc3f60c150e35cea how to do that with Hibernate.

        – Bertl
        Aug 10 '17 at 11:17



















      0














      If you are going to try the above solution https://stackoverflow.com/a/12515543/258544 add the @ReportAsSingleViolation in the annotation defination, this way you will avoid both validation message(one from @Email and one from @Pattern) as it is a composed annotation :



      @Email(message="Please provide a valid email address")
      @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
      @Target( { METHOD, FIELD, ANNOTATION_TYPE })
      @Retention(RUNTIME)
      @Constraint(validatedBy = {})
      @Documented
      @ReportAsSingleViolation


      From @interface ReportAsSingleViolation javax.validation:validation-api:1.1.0.Final) annotation definition :
      "... Evaluation of composed constraints stops on the first validation
      error in case the composing constraint is annotated with ReportAsSingleViolation"






      share|improve this answer































        0














        You can use Email regexp, also making sure that the validation doesn't fail when the email is empty.



        @Email(regexp = ".+@.+\..+|")
        @Target({METHOD, FIELD, ANNOTATION_TYPE})
        @Retention(RUNTIME)
        @Constraint(validatedBy = {})
        @Documented
        public @interface ExtendedEmail {

        @OverridesAttribute(constraint = Email.class, name = "message")
        String message() default "{javax.validation.constraints.Email.message}";

        @OverridesAttribute(constraint = Email.class, name = "groups")
        Class<?> groups() default {};

        @OverridesAttribute(constraint = Email.class, name = "payload")
        Class<? extends Payload> payload() default {};
        }





        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4459474%2fhibernate-validator-email-accepts-askstackoverflow-as-valid%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          8 Answers
          8






          active

          oldest

          votes








          8 Answers
          8






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          33














          Actually, @Email from Hibernate Validator uses regexp internally. You can easily define your own constraint based on that regexp, modified as you need (note the + at the end of DOMAIN):



          @Target({ElementType.FIELD, ElementType.METHOD})
          @Retention(RetentionPolicy.RUNTIME)
          @Constraint(validatedBy = {})
          @Pattern(regexp = Constants.PATTERN, flags = Pattern.Flag.CASE_INSENSITIVE)
          public @interface EmailWithTld {
          String message() default "Wrong email";
          Class<?> groups() default { };
          Class<? extends Payload> payload() default { };
          }

          interface Constants {
          static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
          static final String DOMAIN = "(" + ATOM + "+(\." + ATOM + "+)+";
          static final String IP_DOMAIN = "\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]";

          static final String PATTERN =
          "^" + ATOM + "+(\." + ATOM + "+)*@"
          + DOMAIN
          + "|"
          + IP_DOMAIN
          + ")$";
          }





          share|improve this answer





















          • 17





            True, but I'm a bit surprised that I will need to make a custom validator for what seems like a really common requirement. I'd expect a flag for this kind of thing.

            – jack
            Dec 16 '10 at 15:25











          • A good way to customize some tips and tricks +1 :)

            – ThierryB
            May 22 '13 at 7:36






          • 1





            @Matt solution is much simpler as it only add one line in the annotations

            – Adrien Be
            Oct 1 '13 at 10:24











          • link in this answer is broken.

            – ruruskyi
            Nov 14 '17 at 9:55
















          33














          Actually, @Email from Hibernate Validator uses regexp internally. You can easily define your own constraint based on that regexp, modified as you need (note the + at the end of DOMAIN):



          @Target({ElementType.FIELD, ElementType.METHOD})
          @Retention(RetentionPolicy.RUNTIME)
          @Constraint(validatedBy = {})
          @Pattern(regexp = Constants.PATTERN, flags = Pattern.Flag.CASE_INSENSITIVE)
          public @interface EmailWithTld {
          String message() default "Wrong email";
          Class<?> groups() default { };
          Class<? extends Payload> payload() default { };
          }

          interface Constants {
          static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
          static final String DOMAIN = "(" + ATOM + "+(\." + ATOM + "+)+";
          static final String IP_DOMAIN = "\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]";

          static final String PATTERN =
          "^" + ATOM + "+(\." + ATOM + "+)*@"
          + DOMAIN
          + "|"
          + IP_DOMAIN
          + ")$";
          }





          share|improve this answer





















          • 17





            True, but I'm a bit surprised that I will need to make a custom validator for what seems like a really common requirement. I'd expect a flag for this kind of thing.

            – jack
            Dec 16 '10 at 15:25











          • A good way to customize some tips and tricks +1 :)

            – ThierryB
            May 22 '13 at 7:36






          • 1





            @Matt solution is much simpler as it only add one line in the annotations

            – Adrien Be
            Oct 1 '13 at 10:24











          • link in this answer is broken.

            – ruruskyi
            Nov 14 '17 at 9:55














          33












          33








          33







          Actually, @Email from Hibernate Validator uses regexp internally. You can easily define your own constraint based on that regexp, modified as you need (note the + at the end of DOMAIN):



          @Target({ElementType.FIELD, ElementType.METHOD})
          @Retention(RetentionPolicy.RUNTIME)
          @Constraint(validatedBy = {})
          @Pattern(regexp = Constants.PATTERN, flags = Pattern.Flag.CASE_INSENSITIVE)
          public @interface EmailWithTld {
          String message() default "Wrong email";
          Class<?> groups() default { };
          Class<? extends Payload> payload() default { };
          }

          interface Constants {
          static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
          static final String DOMAIN = "(" + ATOM + "+(\." + ATOM + "+)+";
          static final String IP_DOMAIN = "\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]";

          static final String PATTERN =
          "^" + ATOM + "+(\." + ATOM + "+)*@"
          + DOMAIN
          + "|"
          + IP_DOMAIN
          + ")$";
          }





          share|improve this answer















          Actually, @Email from Hibernate Validator uses regexp internally. You can easily define your own constraint based on that regexp, modified as you need (note the + at the end of DOMAIN):



          @Target({ElementType.FIELD, ElementType.METHOD})
          @Retention(RetentionPolicy.RUNTIME)
          @Constraint(validatedBy = {})
          @Pattern(regexp = Constants.PATTERN, flags = Pattern.Flag.CASE_INSENSITIVE)
          public @interface EmailWithTld {
          String message() default "Wrong email";
          Class<?> groups() default { };
          Class<? extends Payload> payload() default { };
          }

          interface Constants {
          static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
          static final String DOMAIN = "(" + ATOM + "+(\." + ATOM + "+)+";
          static final String IP_DOMAIN = "\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]";

          static final String PATTERN =
          "^" + ATOM + "+(\." + ATOM + "+)*@"
          + DOMAIN
          + "|"
          + IP_DOMAIN
          + ")$";
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 1 '13 at 9:58









          Adrien Be

          12.5k1272121




          12.5k1272121










          answered Dec 16 '10 at 13:28









          axtavtaxtavt

          205k32439440




          205k32439440








          • 17





            True, but I'm a bit surprised that I will need to make a custom validator for what seems like a really common requirement. I'd expect a flag for this kind of thing.

            – jack
            Dec 16 '10 at 15:25











          • A good way to customize some tips and tricks +1 :)

            – ThierryB
            May 22 '13 at 7:36






          • 1





            @Matt solution is much simpler as it only add one line in the annotations

            – Adrien Be
            Oct 1 '13 at 10:24











          • link in this answer is broken.

            – ruruskyi
            Nov 14 '17 at 9:55














          • 17





            True, but I'm a bit surprised that I will need to make a custom validator for what seems like a really common requirement. I'd expect a flag for this kind of thing.

            – jack
            Dec 16 '10 at 15:25











          • A good way to customize some tips and tricks +1 :)

            – ThierryB
            May 22 '13 at 7:36






          • 1





            @Matt solution is much simpler as it only add one line in the annotations

            – Adrien Be
            Oct 1 '13 at 10:24











          • link in this answer is broken.

            – ruruskyi
            Nov 14 '17 at 9:55








          17




          17





          True, but I'm a bit surprised that I will need to make a custom validator for what seems like a really common requirement. I'd expect a flag for this kind of thing.

          – jack
          Dec 16 '10 at 15:25





          True, but I'm a bit surprised that I will need to make a custom validator for what seems like a really common requirement. I'd expect a flag for this kind of thing.

          – jack
          Dec 16 '10 at 15:25













          A good way to customize some tips and tricks +1 :)

          – ThierryB
          May 22 '13 at 7:36





          A good way to customize some tips and tricks +1 :)

          – ThierryB
          May 22 '13 at 7:36




          1




          1





          @Matt solution is much simpler as it only add one line in the annotations

          – Adrien Be
          Oct 1 '13 at 10:24





          @Matt solution is much simpler as it only add one line in the annotations

          – Adrien Be
          Oct 1 '13 at 10:24













          link in this answer is broken.

          – ruruskyi
          Nov 14 '17 at 9:55





          link in this answer is broken.

          – ruruskyi
          Nov 14 '17 at 9:55













          45














          You can also use constraint composition as a work-around. In the example below, I rely on the @Email validator to do the main validation, and add a @Pattern validator to make sure the address is in the form of x@y.z (I don't recommend using just the @Pattern below for regular Email validation)



          @Email(message="Please provide a valid email address")
          @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
          @Target( { METHOD, FIELD, ANNOTATION_TYPE })
          @Retention(RUNTIME)
          @Constraint(validatedBy = {})
          @Documented
          public @interface ExtendedEmailValidator {
          String message() default "Please provide a valid email address";
          Class<?> groups() default {};
          Class<? extends Payload> payload() default {};
          }





          share|improve this answer





















          • 1





            This is indeed the better solution

            – Arefe
            Sep 8 '17 at 6:00
















          45














          You can also use constraint composition as a work-around. In the example below, I rely on the @Email validator to do the main validation, and add a @Pattern validator to make sure the address is in the form of x@y.z (I don't recommend using just the @Pattern below for regular Email validation)



          @Email(message="Please provide a valid email address")
          @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
          @Target( { METHOD, FIELD, ANNOTATION_TYPE })
          @Retention(RUNTIME)
          @Constraint(validatedBy = {})
          @Documented
          public @interface ExtendedEmailValidator {
          String message() default "Please provide a valid email address";
          Class<?> groups() default {};
          Class<? extends Payload> payload() default {};
          }





          share|improve this answer





















          • 1





            This is indeed the better solution

            – Arefe
            Sep 8 '17 at 6:00














          45












          45








          45







          You can also use constraint composition as a work-around. In the example below, I rely on the @Email validator to do the main validation, and add a @Pattern validator to make sure the address is in the form of x@y.z (I don't recommend using just the @Pattern below for regular Email validation)



          @Email(message="Please provide a valid email address")
          @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
          @Target( { METHOD, FIELD, ANNOTATION_TYPE })
          @Retention(RUNTIME)
          @Constraint(validatedBy = {})
          @Documented
          public @interface ExtendedEmailValidator {
          String message() default "Please provide a valid email address";
          Class<?> groups() default {};
          Class<? extends Payload> payload() default {};
          }





          share|improve this answer















          You can also use constraint composition as a work-around. In the example below, I rely on the @Email validator to do the main validation, and add a @Pattern validator to make sure the address is in the form of x@y.z (I don't recommend using just the @Pattern below for regular Email validation)



          @Email(message="Please provide a valid email address")
          @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
          @Target( { METHOD, FIELD, ANNOTATION_TYPE })
          @Retention(RUNTIME)
          @Constraint(validatedBy = {})
          @Documented
          public @interface ExtendedEmailValidator {
          String message() default "Please provide a valid email address";
          Class<?> groups() default {};
          Class<? extends Payload> payload() default {};
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 13 '17 at 7:08









          Andrii Abramov

          4,17643047




          4,17643047










          answered Sep 20 '12 at 15:07









          MattMatt

          2,3651115




          2,3651115








          • 1





            This is indeed the better solution

            – Arefe
            Sep 8 '17 at 6:00














          • 1





            This is indeed the better solution

            – Arefe
            Sep 8 '17 at 6:00








          1




          1





          This is indeed the better solution

          – Arefe
          Sep 8 '17 at 6:00





          This is indeed the better solution

          – Arefe
          Sep 8 '17 at 6:00











          13














          Actually validating e-mail addresses is really complex. It is not possible to validate that an e-mail address is both syntactically correct and addresses the intended recipient in an annotation. The @Email annotation is a useful minimal check that doesn't suffer from the problem of false negatives.



          The next step in validation should be sending an e-mail with a challenge that the user has to complete to establish that the user has access to the e-mail address.



          It is better to be accept a few false positives in step 1 and allow some invalid e-mail addresses to pass through than to reject valid users. If you want to apply additional rules you can add more checks, but be really careful about what you assume to be a requirement of a valid e-mail address. For instance there is nothing in the RFCs that dictates that i@nl would be invalid, because nl is a registered country top-level domain.






          share|improve this answer





















          • 1





            This is the right answer!

            – Artur Czajka
            Aug 18 '17 at 12:54
















          13














          Actually validating e-mail addresses is really complex. It is not possible to validate that an e-mail address is both syntactically correct and addresses the intended recipient in an annotation. The @Email annotation is a useful minimal check that doesn't suffer from the problem of false negatives.



          The next step in validation should be sending an e-mail with a challenge that the user has to complete to establish that the user has access to the e-mail address.



          It is better to be accept a few false positives in step 1 and allow some invalid e-mail addresses to pass through than to reject valid users. If you want to apply additional rules you can add more checks, but be really careful about what you assume to be a requirement of a valid e-mail address. For instance there is nothing in the RFCs that dictates that i@nl would be invalid, because nl is a registered country top-level domain.






          share|improve this answer





















          • 1





            This is the right answer!

            – Artur Czajka
            Aug 18 '17 at 12:54














          13












          13








          13







          Actually validating e-mail addresses is really complex. It is not possible to validate that an e-mail address is both syntactically correct and addresses the intended recipient in an annotation. The @Email annotation is a useful minimal check that doesn't suffer from the problem of false negatives.



          The next step in validation should be sending an e-mail with a challenge that the user has to complete to establish that the user has access to the e-mail address.



          It is better to be accept a few false positives in step 1 and allow some invalid e-mail addresses to pass through than to reject valid users. If you want to apply additional rules you can add more checks, but be really careful about what you assume to be a requirement of a valid e-mail address. For instance there is nothing in the RFCs that dictates that i@nl would be invalid, because nl is a registered country top-level domain.






          share|improve this answer















          Actually validating e-mail addresses is really complex. It is not possible to validate that an e-mail address is both syntactically correct and addresses the intended recipient in an annotation. The @Email annotation is a useful minimal check that doesn't suffer from the problem of false negatives.



          The next step in validation should be sending an e-mail with a challenge that the user has to complete to establish that the user has access to the e-mail address.



          It is better to be accept a few false positives in step 1 and allow some invalid e-mail addresses to pass through than to reject valid users. If you want to apply additional rules you can add more checks, but be really careful about what you assume to be a requirement of a valid e-mail address. For instance there is nothing in the RFCs that dictates that i@nl would be invalid, because nl is a registered country top-level domain.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 13 '17 at 7:08









          Andrii Abramov

          4,17643047




          4,17643047










          answered Oct 13 '14 at 19:59









          DavidDavid

          13112




          13112








          • 1





            This is the right answer!

            – Artur Czajka
            Aug 18 '17 at 12:54














          • 1





            This is the right answer!

            – Artur Czajka
            Aug 18 '17 at 12:54








          1




          1





          This is the right answer!

          – Artur Czajka
          Aug 18 '17 at 12:54





          This is the right answer!

          – Artur Czajka
          Aug 18 '17 at 12:54











          3














          Here's a javax.validation email validator using Apache Commons Validator



          public class CommonsEmailValidator implements ConstraintValidator<Email, String> {

          private static final boolean ALLOW_LOCAL = false;
          private EmailValidator realValidator = EmailValidator.getInstance(ALLOW_LOCAL);

          @Override
          public void initialize(Email email) {

          }

          @Override
          public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
          if( s == null ) return true;
          return realValidator.isValid(s);
          }
          }


          And 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 Email {

          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 {
          Email value();
          }
          }





          share|improve this answer




























            3














            Here's a javax.validation email validator using Apache Commons Validator



            public class CommonsEmailValidator implements ConstraintValidator<Email, String> {

            private static final boolean ALLOW_LOCAL = false;
            private EmailValidator realValidator = EmailValidator.getInstance(ALLOW_LOCAL);

            @Override
            public void initialize(Email email) {

            }

            @Override
            public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            if( s == null ) return true;
            return realValidator.isValid(s);
            }
            }


            And 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 Email {

            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 {
            Email value();
            }
            }





            share|improve this answer


























              3












              3








              3







              Here's a javax.validation email validator using Apache Commons Validator



              public class CommonsEmailValidator implements ConstraintValidator<Email, String> {

              private static final boolean ALLOW_LOCAL = false;
              private EmailValidator realValidator = EmailValidator.getInstance(ALLOW_LOCAL);

              @Override
              public void initialize(Email email) {

              }

              @Override
              public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
              if( s == null ) return true;
              return realValidator.isValid(s);
              }
              }


              And 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 Email {

              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 {
              Email value();
              }
              }





              share|improve this answer













              Here's a javax.validation email validator using Apache Commons Validator



              public class CommonsEmailValidator implements ConstraintValidator<Email, String> {

              private static final boolean ALLOW_LOCAL = false;
              private EmailValidator realValidator = EmailValidator.getInstance(ALLOW_LOCAL);

              @Override
              public void initialize(Email email) {

              }

              @Override
              public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
              if( s == null ) return true;
              return realValidator.isValid(s);
              }
              }


              And 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 Email {

              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 {
              Email value();
              }
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 4 '15 at 21:55









              Neil McGuiganNeil McGuigan

              33.5k890119




              33.5k890119























                  0














                  The constraint composition solution does not work. When Email is used in conjunction with Pattern, the Email regex is held in higher precedence. I believe this is because the Email annotation overrides a few Pattern attributes, namely flags and regexp (the key one here) If I remove @Email, only then will the @Pattern regular expression apply in validations.



                  /**
                  * @return an additional regular expression the annotated string must match. The default is any string ('.*')
                  */
                  @OverridesAttribute(constraint = Pattern.class, name = "regexp") String regexp() default ".*";

                  /**
                  * @return used in combination with {@link #regexp()} in order to specify a regular expression option
                  */
                  @OverridesAttribute(constraint = Pattern.class, name = "flags") Pattern.Flag flags() default { };





                  share|improve this answer






























                    0














                    The constraint composition solution does not work. When Email is used in conjunction with Pattern, the Email regex is held in higher precedence. I believe this is because the Email annotation overrides a few Pattern attributes, namely flags and regexp (the key one here) If I remove @Email, only then will the @Pattern regular expression apply in validations.



                    /**
                    * @return an additional regular expression the annotated string must match. The default is any string ('.*')
                    */
                    @OverridesAttribute(constraint = Pattern.class, name = "regexp") String regexp() default ".*";

                    /**
                    * @return used in combination with {@link #regexp()} in order to specify a regular expression option
                    */
                    @OverridesAttribute(constraint = Pattern.class, name = "flags") Pattern.Flag flags() default { };





                    share|improve this answer




























                      0












                      0








                      0







                      The constraint composition solution does not work. When Email is used in conjunction with Pattern, the Email regex is held in higher precedence. I believe this is because the Email annotation overrides a few Pattern attributes, namely flags and regexp (the key one here) If I remove @Email, only then will the @Pattern regular expression apply in validations.



                      /**
                      * @return an additional regular expression the annotated string must match. The default is any string ('.*')
                      */
                      @OverridesAttribute(constraint = Pattern.class, name = "regexp") String regexp() default ".*";

                      /**
                      * @return used in combination with {@link #regexp()} in order to specify a regular expression option
                      */
                      @OverridesAttribute(constraint = Pattern.class, name = "flags") Pattern.Flag flags() default { };





                      share|improve this answer















                      The constraint composition solution does not work. When Email is used in conjunction with Pattern, the Email regex is held in higher precedence. I believe this is because the Email annotation overrides a few Pattern attributes, namely flags and regexp (the key one here) If I remove @Email, only then will the @Pattern regular expression apply in validations.



                      /**
                      * @return an additional regular expression the annotated string must match. The default is any string ('.*')
                      */
                      @OverridesAttribute(constraint = Pattern.class, name = "regexp") String regexp() default ".*";

                      /**
                      * @return used in combination with {@link #regexp()} in order to specify a regular expression option
                      */
                      @OverridesAttribute(constraint = Pattern.class, name = "flags") Pattern.Flag flags() default { };






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jun 13 '17 at 7:09









                      Andrii Abramov

                      4,17643047




                      4,17643047










                      answered Aug 25 '14 at 19:15









                      user1048931user1048931

                      694




                      694























                          0














                          Obviously I am late to the Party, Still I am replying to this question,



                          Why cant we use @Pattern annotation with regular expressions in our Validation class like this



                          public Class Sigunup {

                          @NotNull
                          @NotEmpty
                          @Pattern((regexp="[A-Za-z0-9._%-+]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")
                          private String email;

                          }


                          Its easier.






                          share|improve this answer


























                          • ... and wrong. "test@myexample..loc" is valid with this regex.

                            – Bertl
                            Aug 8 '17 at 8:47











                          • Can you please elaborate little more ?

                            – user2245151
                            Aug 9 '17 at 9:39











                          • Double-Dots in the domain part are not recognized as wrong. Also, umlaut domains and many more valid email address patterns are not detected as valid. Therefore, it is better to let the validation be performed by special libraries, like Apache Commons EmailValidator. See gist.github.com/robertoschwald/ce23c8c23ebd5b93fc3f60c150e35cea how to do that with Hibernate.

                            – Bertl
                            Aug 10 '17 at 11:17
















                          0














                          Obviously I am late to the Party, Still I am replying to this question,



                          Why cant we use @Pattern annotation with regular expressions in our Validation class like this



                          public Class Sigunup {

                          @NotNull
                          @NotEmpty
                          @Pattern((regexp="[A-Za-z0-9._%-+]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")
                          private String email;

                          }


                          Its easier.






                          share|improve this answer


























                          • ... and wrong. "test@myexample..loc" is valid with this regex.

                            – Bertl
                            Aug 8 '17 at 8:47











                          • Can you please elaborate little more ?

                            – user2245151
                            Aug 9 '17 at 9:39











                          • Double-Dots in the domain part are not recognized as wrong. Also, umlaut domains and many more valid email address patterns are not detected as valid. Therefore, it is better to let the validation be performed by special libraries, like Apache Commons EmailValidator. See gist.github.com/robertoschwald/ce23c8c23ebd5b93fc3f60c150e35cea how to do that with Hibernate.

                            – Bertl
                            Aug 10 '17 at 11:17














                          0












                          0








                          0







                          Obviously I am late to the Party, Still I am replying to this question,



                          Why cant we use @Pattern annotation with regular expressions in our Validation class like this



                          public Class Sigunup {

                          @NotNull
                          @NotEmpty
                          @Pattern((regexp="[A-Za-z0-9._%-+]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")
                          private String email;

                          }


                          Its easier.






                          share|improve this answer















                          Obviously I am late to the Party, Still I am replying to this question,



                          Why cant we use @Pattern annotation with regular expressions in our Validation class like this



                          public Class Sigunup {

                          @NotNull
                          @NotEmpty
                          @Pattern((regexp="[A-Za-z0-9._%-+]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")
                          private String email;

                          }


                          Its easier.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Jul 3 '17 at 10:28

























                          answered Jul 3 '17 at 6:28









                          user2245151user2245151

                          195




                          195













                          • ... and wrong. "test@myexample..loc" is valid with this regex.

                            – Bertl
                            Aug 8 '17 at 8:47











                          • Can you please elaborate little more ?

                            – user2245151
                            Aug 9 '17 at 9:39











                          • Double-Dots in the domain part are not recognized as wrong. Also, umlaut domains and many more valid email address patterns are not detected as valid. Therefore, it is better to let the validation be performed by special libraries, like Apache Commons EmailValidator. See gist.github.com/robertoschwald/ce23c8c23ebd5b93fc3f60c150e35cea how to do that with Hibernate.

                            – Bertl
                            Aug 10 '17 at 11:17



















                          • ... and wrong. "test@myexample..loc" is valid with this regex.

                            – Bertl
                            Aug 8 '17 at 8:47











                          • Can you please elaborate little more ?

                            – user2245151
                            Aug 9 '17 at 9:39











                          • Double-Dots in the domain part are not recognized as wrong. Also, umlaut domains and many more valid email address patterns are not detected as valid. Therefore, it is better to let the validation be performed by special libraries, like Apache Commons EmailValidator. See gist.github.com/robertoschwald/ce23c8c23ebd5b93fc3f60c150e35cea how to do that with Hibernate.

                            – Bertl
                            Aug 10 '17 at 11:17

















                          ... and wrong. "test@myexample..loc" is valid with this regex.

                          – Bertl
                          Aug 8 '17 at 8:47





                          ... and wrong. "test@myexample..loc" is valid with this regex.

                          – Bertl
                          Aug 8 '17 at 8:47













                          Can you please elaborate little more ?

                          – user2245151
                          Aug 9 '17 at 9:39





                          Can you please elaborate little more ?

                          – user2245151
                          Aug 9 '17 at 9:39













                          Double-Dots in the domain part are not recognized as wrong. Also, umlaut domains and many more valid email address patterns are not detected as valid. Therefore, it is better to let the validation be performed by special libraries, like Apache Commons EmailValidator. See gist.github.com/robertoschwald/ce23c8c23ebd5b93fc3f60c150e35cea how to do that with Hibernate.

                          – Bertl
                          Aug 10 '17 at 11:17





                          Double-Dots in the domain part are not recognized as wrong. Also, umlaut domains and many more valid email address patterns are not detected as valid. Therefore, it is better to let the validation be performed by special libraries, like Apache Commons EmailValidator. See gist.github.com/robertoschwald/ce23c8c23ebd5b93fc3f60c150e35cea how to do that with Hibernate.

                          – Bertl
                          Aug 10 '17 at 11:17











                          0














                          If you are going to try the above solution https://stackoverflow.com/a/12515543/258544 add the @ReportAsSingleViolation in the annotation defination, this way you will avoid both validation message(one from @Email and one from @Pattern) as it is a composed annotation :



                          @Email(message="Please provide a valid email address")
                          @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
                          @Target( { METHOD, FIELD, ANNOTATION_TYPE })
                          @Retention(RUNTIME)
                          @Constraint(validatedBy = {})
                          @Documented
                          @ReportAsSingleViolation


                          From @interface ReportAsSingleViolation javax.validation:validation-api:1.1.0.Final) annotation definition :
                          "... Evaluation of composed constraints stops on the first validation
                          error in case the composing constraint is annotated with ReportAsSingleViolation"






                          share|improve this answer




























                            0














                            If you are going to try the above solution https://stackoverflow.com/a/12515543/258544 add the @ReportAsSingleViolation in the annotation defination, this way you will avoid both validation message(one from @Email and one from @Pattern) as it is a composed annotation :



                            @Email(message="Please provide a valid email address")
                            @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
                            @Target( { METHOD, FIELD, ANNOTATION_TYPE })
                            @Retention(RUNTIME)
                            @Constraint(validatedBy = {})
                            @Documented
                            @ReportAsSingleViolation


                            From @interface ReportAsSingleViolation javax.validation:validation-api:1.1.0.Final) annotation definition :
                            "... Evaluation of composed constraints stops on the first validation
                            error in case the composing constraint is annotated with ReportAsSingleViolation"






                            share|improve this answer


























                              0












                              0








                              0







                              If you are going to try the above solution https://stackoverflow.com/a/12515543/258544 add the @ReportAsSingleViolation in the annotation defination, this way you will avoid both validation message(one from @Email and one from @Pattern) as it is a composed annotation :



                              @Email(message="Please provide a valid email address")
                              @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
                              @Target( { METHOD, FIELD, ANNOTATION_TYPE })
                              @Retention(RUNTIME)
                              @Constraint(validatedBy = {})
                              @Documented
                              @ReportAsSingleViolation


                              From @interface ReportAsSingleViolation javax.validation:validation-api:1.1.0.Final) annotation definition :
                              "... Evaluation of composed constraints stops on the first validation
                              error in case the composing constraint is annotated with ReportAsSingleViolation"






                              share|improve this answer













                              If you are going to try the above solution https://stackoverflow.com/a/12515543/258544 add the @ReportAsSingleViolation in the annotation defination, this way you will avoid both validation message(one from @Email and one from @Pattern) as it is a composed annotation :



                              @Email(message="Please provide a valid email address")
                              @Pattern(regexp=".+@.+\..+", message="Please provide a valid email address")
                              @Target( { METHOD, FIELD, ANNOTATION_TYPE })
                              @Retention(RUNTIME)
                              @Constraint(validatedBy = {})
                              @Documented
                              @ReportAsSingleViolation


                              From @interface ReportAsSingleViolation javax.validation:validation-api:1.1.0.Final) annotation definition :
                              "... Evaluation of composed constraints stops on the first validation
                              error in case the composing constraint is annotated with ReportAsSingleViolation"







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jul 18 '18 at 3:43









                              Francisco QuiñonesFrancisco Quiñones

                              2616




                              2616























                                  0














                                  You can use Email regexp, also making sure that the validation doesn't fail when the email is empty.



                                  @Email(regexp = ".+@.+\..+|")
                                  @Target({METHOD, FIELD, ANNOTATION_TYPE})
                                  @Retention(RUNTIME)
                                  @Constraint(validatedBy = {})
                                  @Documented
                                  public @interface ExtendedEmail {

                                  @OverridesAttribute(constraint = Email.class, name = "message")
                                  String message() default "{javax.validation.constraints.Email.message}";

                                  @OverridesAttribute(constraint = Email.class, name = "groups")
                                  Class<?> groups() default {};

                                  @OverridesAttribute(constraint = Email.class, name = "payload")
                                  Class<? extends Payload> payload() default {};
                                  }





                                  share|improve this answer




























                                    0














                                    You can use Email regexp, also making sure that the validation doesn't fail when the email is empty.



                                    @Email(regexp = ".+@.+\..+|")
                                    @Target({METHOD, FIELD, ANNOTATION_TYPE})
                                    @Retention(RUNTIME)
                                    @Constraint(validatedBy = {})
                                    @Documented
                                    public @interface ExtendedEmail {

                                    @OverridesAttribute(constraint = Email.class, name = "message")
                                    String message() default "{javax.validation.constraints.Email.message}";

                                    @OverridesAttribute(constraint = Email.class, name = "groups")
                                    Class<?> groups() default {};

                                    @OverridesAttribute(constraint = Email.class, name = "payload")
                                    Class<? extends Payload> payload() default {};
                                    }





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      You can use Email regexp, also making sure that the validation doesn't fail when the email is empty.



                                      @Email(regexp = ".+@.+\..+|")
                                      @Target({METHOD, FIELD, ANNOTATION_TYPE})
                                      @Retention(RUNTIME)
                                      @Constraint(validatedBy = {})
                                      @Documented
                                      public @interface ExtendedEmail {

                                      @OverridesAttribute(constraint = Email.class, name = "message")
                                      String message() default "{javax.validation.constraints.Email.message}";

                                      @OverridesAttribute(constraint = Email.class, name = "groups")
                                      Class<?> groups() default {};

                                      @OverridesAttribute(constraint = Email.class, name = "payload")
                                      Class<? extends Payload> payload() default {};
                                      }





                                      share|improve this answer













                                      You can use Email regexp, also making sure that the validation doesn't fail when the email is empty.



                                      @Email(regexp = ".+@.+\..+|")
                                      @Target({METHOD, FIELD, ANNOTATION_TYPE})
                                      @Retention(RUNTIME)
                                      @Constraint(validatedBy = {})
                                      @Documented
                                      public @interface ExtendedEmail {

                                      @OverridesAttribute(constraint = Email.class, name = "message")
                                      String message() default "{javax.validation.constraints.Email.message}";

                                      @OverridesAttribute(constraint = Email.class, name = "groups")
                                      Class<?> groups() default {};

                                      @OverridesAttribute(constraint = Email.class, name = "payload")
                                      Class<? extends Payload> payload() default {};
                                      }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 20 '18 at 16:47









                                      DavithbulDavithbul

                                      1




                                      1






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4459474%2fhibernate-validator-email-accepts-askstackoverflow-as-valid%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          MongoDB - Not Authorized To Execute Command

                                          How to fix TextFormField cause rebuild widget in Flutter

                                          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith