5.2.9. Entry Widget Validation
You can perform input validation as characters are typed in an Entry
widget, although, by default, validation is disabled. You enable
validation using the -validate option, specifiying
what events trigger your validation subroutine. The possible values
for this option are focus and
focusin (when the Entry gets the keyboard focus),
focusout (when the Entry loses focus),
key (on any key press), or all.
The -validatecommand callback should return true
to accept the input or false to reject it. When false is returned,
the -invalidcommand callback is executed.
The -validatecommand and
-invalidcommand callbacks are called with these
arguments:
-
The proposed value of the Entry (the value of the text variable too)
-
The characters to be added or deleted; undef if
called due to focus, explicit call, or change in text variable
-
The current value before the proposed change
-
The index of the string to be added/deleted, if any; otherwise, -1
-
The type of action: 1 for insert, 0 for delete, -1 if a forced
validation or text variable validation
This Entry ensures that characters are restricted to those in the
string "perl/Tk", without regard to case:
my $e = $mw->Entry(
-validate => 'key',
-validatecommand => sub {$_[1] =~ /[perl\/Tk]/i},
-invalidcommand => sub {$mw->bell},
)->pack;