Recent Changes - Search:



edit SideBar


If you are using a GUI, you will quickly find that all the fields you type into are text fields. But if your code requires a numeric value, you can't just send it a string.

Here's a way to validate text as convertible into a number (an integer or float). It is not 100% foolproof (it needs more testing), but it works for the basic 'bad entries':

  • one or more letters are put in the text box ('123x')
  • a float between -1.0 and 1.0 is malformed because it doesn't have a leading zero. (.33 instead of 0.33)

Here is an example, taken from MyGUI>>setHeaterAdjustment

 heaterAdjustmentNumber := [heaterAdjustment getText asNumber.]
   on: Error do: 
     [Transcript cr; show: 'Invalid entry.  '. 
       self setMyViewer: 
         String crlf, '**Invalid entry.  Numbers only. Floats require a 0 before the

The block in the first line '[heaterAdjustment getText asNumber.]' tries to convert the text inputted into a number. If asNumber fails, it throws an exception. That exception is caught, and a message is sent to the user. It's a guess what the real reason for the error is, so both are given.

Other reasons for rejecting the otherwise valid entry are done separately. For example, if the value should be > 0:

  (myControl setHeaterAdjustment: heaterAdjustmentNumber) 
      [self setMyViewer: 
        String crlf, '**heaterAdjustment is set to: ', myControl heaterAdjustment
      [self setMyViewer: 
        String crlf, '**heaterAdjustment is unchanged. Must be > 0'.]

In this case the requirement of the value being > 0 is handled elsewhere (in MyControl>>setHeaterAdjustment). All we see here is the message input to the user, depending on success or failure.

In MyControl>>setHeaterAdjustment:aNumber, there's this conditional statement:

 setHeaterAdjustment: aNumber
  "change the effect of the heater. Must be a positive number. Should be
  small like 0.2"
  "return value true/false is used by MyGUI>>setHeaterAdjustment:"

  aNumber >= 0 
    ifTrue: [self heaterAdjustment: aNumber.
      Transcript cr; show: '**heater factor has been set to: ', aNumber asString.
    ifFalse: [Transcript cr; show:  '**Not changed. Heater adjustment must be a
    positive number**'.
Edit - History - Print - Recent Changes - Search
Page last modified on May 01, 2011, at 11:57 AM