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.text.*;
013import java.util.regex.*;
014
015import fc.jdbc.*;
016import fc.io.*;
017import fc.util.*;
018
019/**
020Validates a time entered in a text box. Typical examples may
021look like: <tt>1:23 pm</tt>, <tt>1 am</tt>, <tt>1:00 am</tt>,
022and <tt>01:23 pm</tt> (with or without "am/pm" as part of the
023entered text). By default, all of the above patterns are allowed and
024the space between the time and "am/pm" is optional. This can be
025changed via the {@link #useAM_PM} and {@link #allowSpaceBeforeAM_PM}
026methods.
027
028@author hursh jain
029**/
030public final class VTime extends FieldValidator
031{
032boolean useAM_PM = true;
033boolean allow_space = true;
034
035public VTime(AbstractText field, String errorMessage)
036  {
037  super(field, errorMessage);
038  }
039
040public void useAM_PM(boolean useAM_PM)
041  {
042  this.useAM_PM = useAM_PM;
043  }
044
045public void allowSpaceBeforeAM_PM(boolean allow)
046  {
047  this.allow_space = allow;
048  }
049    
050/** 
051Works with any field that returns a <b>String</b> via it's {@link
052Field#getValue} method.
053<p>
054If validation succeeds, this method puts the parsed date in the specified
055form data as the validated value for the target field. This saves the
056hassle of reparsing the text when (typically) retrieving it later to save
057the value out to the database.
058
059@throws ClassCastException  If the field's {@link Field#getValue} method
060              does not return a String
061**/
062public boolean validate(FormData fd, HttpServletRequest req) 
063  {
064  String val = ((AbstractText) field).getValue(fd);
065  
066  if (val == null)
067    return false;
068    
069  boolean result = true;
070
071  DateFormat df1 = null, df2 = null;
072
073  if (useAM_PM) 
074    {
075    df1 = new SimpleDateFormat("h:mma");
076    if (allow_space) {
077      df2 = new SimpleDateFormat("h:mm a");
078      }
079    }
080  else
081    df1 = new SimpleDateFormat("h:mm");
082  
083  Date date = null;
084  
085  try {
086    date = df1.parse(val);    
087    }
088  catch (Exception e) 
089    {
090    if (df2 != null) {
091      try {
092        date = df2.parse(val);
093        }
094      catch (Exception e2) {
095        }
096      }
097    }
098  
099  if (date == null)
100    result = false;
101  else
102    fd.putValidatedData(field.getName(), date);
103
104  return result;
105  } 
106
107}          //~class VDate
108