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 006package fc.web.forms; 007 008import javax.servlet.*; 009import javax.servlet.http.*; 010import java.io.*; 011import java.util.*; 012import java.util.regex.*; 013 014import fc.jdbc.*; 015import fc.io.*; 016import fc.util.*; 017 018/** 019Validates a email address 020 021@author hursh jain 022**/ 023public final class VEmail extends FieldValidator 024{ 025boolean allowEmpty; 026 027/** 028Constructs a new email validator that does not allow empty 029email address as valid 030**/ 031public VEmail(AbstractText field, String errorMessage) 032 { 033 this(field, errorMessage, false); 034 } 035 036/** 037Constructs a new email validator that allows an empty email 038address as valid if the <tt>allowEmpty</tt> argument is 039<tt>true</tt>. This is useful for optional email fields. 040**/ 041public 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 048final static Pattern EmailPattern = Pattern.compile(".+@.+\\..+"); 049 050/** 051Works 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**/ 056public 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