Ensuring numeric input

Michael J. Lew michaell at unimelb.edu.au
Wed Oct 26 20:34:45 EDT 2005


How can I prevent users from being able to make non-number values in 
a field? Simply preventing non-numeric keys is not enough because I 
need to prevent things that use characters that are in valid numbers 
to make non-numbers like 1.2.3 or -1.2-3.

I thought it would be relatively easy, but it might not be. Here is 
the field script of a surprisingly complicated attempt:

on keydown thekey
   if theKey is in "0123456789-." then --may be an allowable input
     -- but I still need to check whether the result would be a valid number.
     put value(the selectedLine) into thisLine --current number
     put length(thisLine) into thisLineLen
     put the selectedCHunk into sc --returns character locations from 
start of field
    
     --Need to find where the current line starts
     put offset(thisLine,me,min(0,word 2 of sc-thislinelen)) into thisLineStart
     --The characters to skip bit is an attempt to prevent the offset function
     --  from returning a match to an earlier line in the field.
     --  It needs the min function to prevent negative values.
    
     --Now see if the input would make a non-numeric result
     --First find where the selection point is in the line
     put word 2 of sc +1 - thisLineStart into theSelectionStartChar
     put word 4 of sc +1 - thisLineStart into theSelectionEndChar
     --I don't know why I had to add one to the values...
     put thisLineStart & return & theSelectionStartChar && theSelectionEndCHar
     --Now test the input in the relevant place
     put theKey into char theSelectionStartChar to theSelectionEndChar 
of thisLine
    
     --next line to help debugging
     --put  thisLine & return & thisLineStart & return & 
theSelectionStartChar && theSelectionEndChar
    
     if thisLine & "0" is a number then --should be OK
       --Needs the appended zero to allow a line to start with a decimal point.
       pass KeyDown
     end if
   end if
end keydown


It seems to work, but it's an extraordinarily long and winding road 
to get to a simple end-point. What am I missing?

Thanks,
Michael

-- 
Michael J. Lew

Senior Lecturer
Department of Pharmacology
The University of Melbourne
Parkville 3010 put "-1" is a number
Victoria
Australia

Phone +613 8344 8304

**
New email address: michaell at unimelb.edu.au
**



More information about the Use-livecode mailing list