001    // Copyright (c) 2001 Hursh Jain (http://www.mollypages.org) 
002    // The Molly framework is freely distributable under the terms of an
003    // MIT-style license. For details, see the molly pages web site at:
004    // http://www.mollypages.org/. Use, modify, have fun !
005    
006    package fc.web.forms;
007    
008    import javax.servlet.*;
009    import javax.servlet.http.*;
010    import java.io.*;
011    import java.util.*;
012    import java.util.regex.*;
013    
014    import fc.jdbc.*;
015    import fc.io.*;
016    import fc.util.*;
017    
018    /**
019    Validates a email address
020    
021    @author hursh jain
022    **/
023    public final class VEmail extends FieldValidator
024    {
025    boolean     allowEmpty;
026    
027    /** 
028    Constructs a new email validator that does not allow empty
029    email address as valid
030    **/
031    public VEmail(AbstractText field, String errorMessage)
032      {
033      this(field, errorMessage, false);
034      }
035    
036    /**  
037    Constructs a new email validator that allows an empty email
038    address as valid if the <tt>allowEmpty</tt> argument is
039    <tt>true</tt>. This is useful for optional email fields.
040    **/
041    public VEmail(AbstractText field, String errorMessage, boolean allowEmpty)
042      {
043      super(field, errorMessage);
044      this.allowEmpty = allowEmpty;
045      }
046    
047    //all top level domains are at least 2 chars
048    final static Pattern EmailPattern = Pattern.compile(".+@.+\\..+");
049      
050    /** 
051    Works with any field that returns a String via it's {@link Field#getValue} method. 
052    
053    @throws ClassCastException  If the field's {@link Field#getValue} method
054                  does not return a String
055    **/
056    public boolean validate(FormData fd, HttpServletRequest req) 
057      {
058      String val = ((AbstractText)field).getValue(fd);
059        
060      //val == null different from an empty string
061      if (val == null)
062        return false;
063    
064      if (allowEmpty && val.equals(""))
065        return true;
066    
067      Matcher matcher = EmailPattern.matcher(val);  
068      boolean valid = matcher.matches();
069      return valid;
070      } 
071    
072    }          //~class VEmail
073