devxlogo

Correction to the Tip “Email Address Validation Using a Regular Expression”

Correction to the Tip “Email Address Validation Using a Regular Expression”

There tip corrects a problem with the previously published tip Email Address Validation Using a Regular Expression. The problem with the original version is that when you enter an email address such as (for example) [email protected], the the function incorrectly returns true. The problem is in the country code. Here’s a corrected version:

public boolean validateEmail(email){   // Input the string for validation   // String email = "[email protected]";   // Set the email pattern string   Pattern p = Pattern.compile(".+@.+\.[a-z]+");   // Match the given string with the pattern   Matcher m = p.matcher(email.getText());   // check whether match is found   boolean matchFound = m.matches();   StringTokenizer st = new StringTokenizer(email, ".");   String lastToken = null;   while (st.hasMoreTokens()) {      lastToken = st.nextToken();   }   if (matchFound && lastToken.length() >= 2      && email.length() - 1 != lastToken.length()) {      // validate the country code      return true;   }   else return false;}

devx-admin

Share the Post: