简体   繁体   中英

Email verification in java

Is there any regex to validate email which disallow .com.com ie 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");
      } 

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM