tclbwidget

Validate entry with BWidget's ComboBox


The BWidget ComboBox widget allows you to fill in an entry field with a value. I would like to enforce only specific characters in that field (e.g. only [a-z0-9]). For that purpose I would like to use Tcl/Tk's -validatecommand (or -vcmd for short), just as you do with the standard 'entry' widget:

proc ValidateMyEntry { value } {
    # Check if it's alphanum string

    if ![regexp {^[-a-zA-Z0-9]*$} $value] {
        return 0
    }
    return 1
}

entry .my_entry -width 20 -textvariable myVar -validate key -vcmd {ValidateMyEntry %P}

It seems ComboBox does not support -validatecommand. What's the best work-around?


Solution

  • As something that was possible but a bit cumbersome, I decided to use the old-style 'trace variable' function to enforce values in combobox.

    Put the following statement after the ComboBox call:

    trace variable myVar w forceAlphaNum
    

    Elsewhere, you have to define the forceAlphaNum proc:

    proc forceAlphaNum { name el op } {
        if { $el == "" } {
            set newname $name
            set oldname ${name}_alphanum
        } else {
            set newname ${name}($el)
            set oldname ${name}_alphanum($el)
        }
    
        global $newname
        global $oldname
    
        if { ![info exist $oldname] } {
            set $oldname ""
        }    
    
        # Check if it's alphanum string
        if ![regexp {^[a-zA-Z0-9]*$} [set $newname]] {
            set $newname [set $oldname]
            bell; return
        }
        set $oldname [set $newname]
    }