I found Jon’s script when looking for ways to validate a user entered date.
I cannot determine whether it was safe when written, but it has a hole in Snow Leopard (AppleScript 2.1.2):
set validResult to (run script (("get " & typeClass) as text) & " \"" & theResult & "\"")
This will accept any day up to 31, regardless of the month, and overflow will occur with months with less than 31 days.
I added a test to compare the entered month with that of valid_result:
-- default answer reflects expected format
set theDate to validateInput("Enter a date:", "20/8/05", date) -->date "zaterdag 20 augustus 2005 00:00:00"
on validateInput(thePrompt, defaultAnswer, typeClass)
set {theError, theIcon} to {"", 1}
repeat
try
set theResult to text returned of (display dialog theError & thePrompt default answer defaultAnswer buttons {"Cancel", "OK"} default button 2 with icon theIcon)
try
set validResult to (run script "get \"" & theResult & "\" as " & typeClass as text)
return validResult
on error
try
-- If here it's a date; must perform test to prevent overflow
-- The 'run script' will accept any day up to 31,
-- regardless of the month, and overflow may occur
set validResult to (run script (("get " & typeClass) as text) & " \"" & theResult & "\"")
-- Check if its month is same as entered month
-- make it so it works for both dd/mm and mm/dd format
-- As the day is always 29, 30 or 31 with this error
-- a situation where month & day are the same integer should not occur
set text item delimiters to "/"
set {firstItem, secondItem} to {text item 1, text item 2} of theResult
set text item delimiters to ""
set monthResult to month of validResult as integer
if (monthResult ≠(firstItem as integer)) and (monthResult ≠(secondItem as integer)) then
-- overflow occurred, it's not the entered date
beep
error -- up a level...
else -- it's valid, return result
return validResult
end if
error -- ...and up...
end try
error "Overflow error!" -- tell 'm
end try
return validResult -- undefined - raises error
on error e number n
if n = -128 then return defaultAnswer
-- implicit coercion of typeClass
set {theError, theIcon} to {""" & theResult & "" is not a valid " & typeClass & ". Please try again." & return & return, 2}
if e = "Overflow error!" then set theError to e & return & theError
end try
end repeat
end validateInput
(and eliminated the class list, as AppleScript 2 has only class text)
It seems to work.It is, however, less forgiving as Jon’s script. Jon’s routine accepts various separators without change (I tried dash, dot, comma) - you can even mix them.
I could not find any info on the year range when entered as yy.
This seems to be the boundary:
-- 1/1/50 > 1 jan 2050
-- 2/1/50 > 2 jan 1950
Anything with yy > 50 evaluates as 19yy, and yy < 50 becomes 20yy.
A leading zero is required with single-digit years, but not month or day; you’ll get ‘0005’ when ‘5’ is entered for the year.