scanning for numerals / letters
Gerard Flanagan
grflanagan at yahoo.co.uk
Wed Apr 19 07:19:03 EDT 2006
Kun wrote:
> I have the following if statement that checks if a form is empty:
>
> if form.has_key("date") and form["date"].value != "":
> date=form['date'].value
>
> else:
> print "ERROR: No date entered!"
> raise Exception
>
> I would also like to add another if statement checking if 'date' has any
> letters (a-z) in it, and if so, would like to say that "you have to
> enter a date with numbers". I am not sure how to alter my current if
> statement to do that check so any assistance would be appreciated.
>
Having just attempted a 'string_to_date' function I can see the wisdom
of having separate 'day', 'month' and 'year' input fields on the
client. If you can't or won't provide separate fields then I suppose
you have to inform users as to what you accept as valid input, eg.
'ddmmyy', or 'month/day/year'. Here's some code which assumes that you
are providing appropriate formatting hints:
import time
import datetime
DDMMYY = ['%d %m %Y', '%d %m %y', '%d/%m/%Y', '%d/%m/%y', '%d-%m-%Y',
'%d-%m-%y' ]
def yearmonthday(datestring, fmts=DDMMYY):
ymd = tuple()
for f in fmts:
try:
ymd = time.strptime( datestring, f )
break
except ValueError:
continue
if not ymd:
raise ValueError
return ymd[0], ymd[1], ymd[2]
def is_valid_date(datestring, fmts=DDMMYY):
try:
yearmonthday(datestring, fmts)
return True
except ValueError:
return False
def string_to_date(datestring, fmts=DDMMYY):
return datetime.date( *yearmonthday(datestring, fmts) )
assert string_to_date( '1/2/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1 2 01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '01/02/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1/02/2001', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '29/02/2008', DDMMYY) ==
datetime.date(2008,2,29)
assert string_to_date( '01/2/99', DDMMYY) == datetime.date(1999,2,1)
for d in [ '', '32/1/01', '01/13/01', '29/2/07', '1/2', 'abcdef' ]:
assert not is_valid_date(d, DDMMYY)
Gerard
More information about the Python-list
mailing list