PDA

View Full Version : AppleScript: Requiring user input to be a number


LingaringBell
11-03-2007, 01:28 AM
Hey Guys,
I'm using a simple:

set x to display dialog "blah blah blah" default answer ""

However, I need the user to input only a number, so if somebody accidentally fat fingers a letter an error will occur. I can't use an "on error" statement because I have to input the exact error that will come up, and that error message would of course depend on what the user accidentally entered. Any suggestions? Thanks as always.
-Bell

bramley
11-03-2007, 05:00 AM
try/on error/end try handlers don't just respond to the error string, but also to error codes (or numbers.) Use 'on error number' instead of 'on error'

Code below. You ought to improve how the script handles the error message.
set isInputValid to false
repeat until isInputValid
set response to display dialog "blah blah" default answer "0"
try
set theNumber to (text returned of response) as number
set isInputValid to true
on error number errorNumber
if (errorNumber = -1700) then
display dialog "INVALID INPUT. TRY AGAIN."
end if
end try
end repeat

tw
11-03-2007, 01:50 PM
slightly more user-friendly tweak on bramley's code... :)

set displayString to "Please input a number"
set defaultAnswer to 0
repeat
set response to display dialog displayString default answer defaultAnswer
try
set theNumber to (text returned of response) as number
exit repeat
on error errstr
set displayString to errstr & return & "Please try again."
set defaultAnswer to text returned of response
end try
end repeat