Validating gnocl::entry Values

WJG (26-Apr-09) Gnocl supports the GtkEntry widget through the gnocl::entry binding. The Gtk core code however provides no functionality for input validation as it is assumed that the author will perform validation checks on the overall string associated with the entry. With this in mind, the following script example shows how the content of the gnocl::entry can be checked once the 'activated' signal is emitted (i.e. the user presses the Enter key). The script is only an example and many more other checks (i.e. punctuation and non alpha-characters) could also be applied.

# EntryValidate.tcl
#!/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "[email protected]"
package require Gnocl

proc validate { entry {type int} } {

    set value [$entry get -value]

    switch $type {
        int {
            if { [ regsub -all {[a-z]} [string tolower $value] {} temp] != 0} {
                puts "ERROR"
            } else {
                puts "ENTRY OK"
            }
        }
        alpha {
            if { [ regsub -all {[0-9]} $value {} temp] != 0} {
                puts "ERROR"
            } else {
                puts "ENTRY OK"
            }
        }
        default {
            puts "SOMETHING ELSE"
        }
    }

}

set default1 100
set default2 ABC

# note the entry value will only be set when Enter button presssed, this
# coresponds to the -onActivate signal
set entry1 [gnocl::entry \
    -variable entryText1 \
    -value $default1 \
    -onActivate { validate %w } \
]

set entry2 [gnocl::entry \
    -variable entryText2 \
    -value $default2 \
    -onActivate { validate %w alpha} \
]

set box [gnocl::box -children [list $entry1 $entry2] ]

gnocl::window -title "Entry" -child $box

gnocl::mainLoop