0

I have found out that I could validate email input using regular expressions. However, I do not know where do I place the expressions. Do i put them in my java controller methods, entity classes or JSP?

gymcode
  • 4,431
  • 15
  • 72
  • 128
  • Why don't you just use the commons validator? – Artefacto Aug 16 '11 at 15:55
  • 1
    please refer to the following question, just to give some proportions: http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses – MByD Aug 16 '11 at 15:55
  • @Artefacto commons validator? Is that an import or? I'm a java newbie > – gymcode Aug 16 '11 at 15:58
  • 1
    @RUi See http://commons.apache.org/validator/apidocs/index.html You'll have to use an extra library though. – Artefacto Aug 16 '11 at 16:00

4 Answers4

0

If your email is in a string, you might write something like the following to validate the email:

String email;
.
.  // load the email string
. 
if (email.matches("^[A-Za-z0-9_.]+[@][A-Za-z.]+$"))
{
.
.
.
}
else
    throw new EmailNotValidException();
djhaskin987
  • 9,741
  • 4
  • 50
  • 86
0

I think you can create some EmailValidatorClass class which you can use in your project whenever you need to validate email addresses:

import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import java.util.StringTokenizer;

/**
  * A class to provide stronger validation of email addresses.      
  *
  */
 public class EmailAddressValidator
 {
   public static boolean isValidEmailAddress(String emailAddress)
   {
     // a null string is invalid
     if ( emailAddress == null )
       return false;

     // a string without a "@" is an invalid email address
     if ( emailAddress.indexOf("@") < 0 )
       return false;

     // a string without a "."  is an invalid email address
     if ( emailAddress.indexOf(".") < 0 )
       return false;

     if ( lastEmailFieldTwoCharsOrMore(emailAddress) == false )
       return false;

     try
     {
       InternetAddress internetAddress = new InternetAddress(emailAddress);
       return true;
     }
     vcatch (AddressException ae)
     {
       // log exception
            return false;
     }
   }


   /**
    * Returns true if the last email field (i.e., the country code, or something
    * like .com, .biz, .cc, etc.) is two chars or more in length, which it really
    * must be to be legal.
    */
   private static boolean lastEmailFieldTwoCharsOrMore(String emailAddress)
   {
     if (emailAddress == null) return false;
     StringTokenizer st = new StringTokenizer(emailAddress,".");
     String lastToken = null;
     while ( st.hasMoreTokens() )
     {
       lastToken = st.nextToken();
     }

     if ( lastToken.length() >= 2 )
     {
       return true;
     }
     else
     {
       return false;
     }
   }
 }
adritha84
  • 957
  • 1
  • 7
  • 15
0
String expression = "[A-Za-z]+@+[A-Za-z]+\\.+[A-Za-z]{2,4}+$";
Pattern p = Pattern.compile(expression);
Matcher m = p.matcher(txtValidate.getText());
if(!m.matches())
{
JOpyionPane.showMessageDialog(null, "Email not valid");
}
Imran Ali
  • 59
  • 2
  • 10
0

It is not possible to create correct email validation solely by using regular expressions.

Here is a description on how to (almost) correctly validate email addresses.


Emails are validated according to RFC 5321 and RFC 5322. The following is simplified formal definition of the email syntax:

addr-spec = local-part "@" domain
local-part = dot-atom-text / quoted-string
dot-atom-text = atom *("." atom)
atom = 1*atext
atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
ALPHA = ASCII characters in the range ‘a’ (ACSII code 0x61) through ‘z’ (ACSII code 0x7A) and ‘A’ (ACSII code 0x41) through ‘Z’ (ACSII code 0x5A)
DIGIT = ASCII characters in the range ‘0’ (ACSII code 0x30) through ‘9’ (ACSII code 0x39)
specials = "(" / ")" / "<" / ">" / "[" / "]" / ":" / ";" / "@" / "\" / "," / "."
quoted-string = “ *(qcontent) “
qcontent = qtext / quoted-pair
qtext = 0x21 / 0x23-0x5B / 0x5D-0x7E; All ASCII printable characters instead of “ and \
quoted-pair = \ (VCHAR / WSP)
VCHAR = 0x21-0x7E; All ASCII printable characters
WSP = 0x20 / 0x09; ASCII Space or tab characters

In addition to these rules the quoted-pair can be placed anywhere inside the local-part. Note that the specials group of characters is not used. These characters cannot present neither in the local-part nor in the domain part of the email. The local-part can be up to 64 characters in length and the domain part may be up to 255 characters (if it should be a valid DNS domain name) as long as the combined length of the whole email is less than 256 characters.

Domain names are validated according to RFC 1034 and RFC 1123. The following is formal definition of the domain name syntax:

domain = subdomain / " " 
subdomain = label / subdomain "." label
label = let-dig *(*(ldh-str) let-dig)
ldh-str = let-dig-hyp / let-dig-hyp ldh-str
let-dig-hyp = let-dig / "-"
let-dig = ALPHA / DIGIT

Additionally RFC 1034 limits the domain to 255 ASCII symbols and the label to 63 ASCII symbols.

The Apache commons validation library (mentioned in the comments of the question) is a good start. It contains both domain validation and email validation, although the last time I have checked it had a few bugs in the email validation.

Community
  • 1
  • 1
ShaMan-H_Fel
  • 2,139
  • 17
  • 24