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.text.*; 013 import java.util.regex.*; 014 015 import fc.jdbc.*; 016 import fc.io.*; 017 import fc.util.*; 018 019 /** 020 Validates a time entered in a text box. Typical examples may 021 look like: <tt>1:23 pm</tt>, <tt>1 am</tt>, <tt>1:00 am</tt>, 022 and <tt>01:23 pm</tt> (with or without "am/pm" as part of the 023 entered text). By default, all of the above patterns are allowed and 024 the space between the time and "am/pm" is optional. This can be 025 changed via the {@link #useAM_PM} and {@link #allowSpaceBeforeAM_PM} 026 methods. 027 028 @author hursh jain 029 **/ 030 public final class VTime extends FieldValidator 031 { 032 boolean useAM_PM = true; 033 boolean allow_space = true; 034 035 public VTime(AbstractText field, String errorMessage) 036 { 037 super(field, errorMessage); 038 } 039 040 public void useAM_PM(boolean useAM_PM) 041 { 042 this.useAM_PM = useAM_PM; 043 } 044 045 public void allowSpaceBeforeAM_PM(boolean allow) 046 { 047 this.allow_space = allow; 048 } 049 050 /** 051 Works with any field that returns a <b>String</b> via it's {@link 052 Field#getValue} method. 053 <p> 054 If validation succeeds, this method puts the parsed date in the specified 055 form data as the validated value for the target field. This saves the 056 hassle of reparsing the text when (typically) retrieving it later to save 057 the value out to the database. 058 059 @throws ClassCastException If the field's {@link Field#getValue} method 060 does not return a String 061 **/ 062 public 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