How to validate user input as integer, then confirm that integer is a specific length using Apple Script

applescript

I'm building an Apple Script to prompt and receive input from a user via a dialog box. The default answer of the dialog is "Enter Code". The required input is a 6-digit code given to each user. On receiving the user's input (or code), some validation checks need to occur confirming that the user's input is acceptable based on the following conditions:

  1. User can't enter letters or symbols.

  2. Input must be in an integer (whole numbers only, and yes zero counts).

  3. The code (input), just be exactly (or equal to) 6 digits long. No more or no less than 6.

Background – the user's code is generated ad-hoc from another application and is unique each time. There is no way to cross reference this code.


For example, the user enters 123456 into the dialog box. Using Apple Script, how can I script this, ensuring again, that the code is all numbers, and precisely 6 digits long?

Best Answer

Solution 1:

set input to "123456"

if the length of the input ≠ 6 ¬
    then return "Wrong number of characters."

try
    if "0123456789" does not contain item 1 of the input ¬
        or item -1 of the input is in [space, tab, linefeed] ¬
        then error
    
    set input to input as number
    
    if class of the input ≠ integer then error
on error
    return "Invalid characters."
end try



text -6 thru -1 of ("000000" & the input)

Solution 2:

This solution benefits from being extremely short, but also treats the problem as it ought to be treated. It's a misnomer to say you wish to "validate user input as integer", when, in fact, we are only ever dealing with text. The passcode is a 6-character passcode, and those characters are limited to the unicode values that represent digits; but they are still text characters, and not integers in any numerical sense.

Mark's comment against the question actually stated this, but even I fell into the mindset of wanting to assess the input as numbers, which is partly what Solution 1 above does; and it works, and it is a perfectly good solution, but it performs needless steps to get to the end result.

Treating the input purely as text, the problem, so succinctly stated by Mark is to "Check the string is 6 characters and each of those is in range 0-9." So that's exactly what this solution does, in one simple line:

set input to "123456"

set validation to do shell script ¬
    "egrep -x '[0-9]{6}' <<<" & ¬
    quoted form of the input & ¬
    "|| echo Invalid input"

The variable validation will either contain the 6-digit code if it is valid, or "Invalid input" otherwise.