0

Is there any regex to validate email which disallow .com.com i.e example@example.com.com but allow .com.uk? I have pasted my code that should return false while user enters .com.com. Can anyone verify my code below?

String ePattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern p =Pattern.compile(ePattern);
Matcher m = p.matcher(studentemail);
b= m.matches();
    if(!b) {
        eMsg.addError("email must be in formate: example@example.xxx / example@example.xx");
        request.setAttribute("errorMessage", eMsg);
        requestDispatcher = request.getRequestDispatcher("/addrecord.jsp");
        requestDispatcher.forward(request, response);
        return;
    }   

     else {
           System.out.println("valid email id");
      } 
Saugat Bhattarai
  • 2,614
  • 4
  • 24
  • 33
M Hamza Javed
  • 1,269
  • 4
  • 17
  • 31
  • 6
    Possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – 1615903 Nov 09 '16 at 10:58

1 Answers1

3

Such a regex isn't limited to Java in most cases (only if special capabilities are used that are not supported by the Java regex engine). Besides that, if you want to match @example.xx only you should adjust the second part of your regex (especially the first group in that part). But note that there are domains like xxx.co.uk which might not be valid then.

Also xx.com.com might be an invalid domain but it also might not (at least in other combinations, e.g. de.de is a valid domain) so you might want to either allow that, test for specific combinations only or restrict usage of such domains.

However, depending on your use-case it would probably be better to send a confirmation email since a regex can just tell you that it looks correct but there might still be errors.

Thomas
  • 87,414
  • 12
  • 119
  • 157