I'm trying to create a Tk::Entry widget in my program that will accept a floating point value with two decimal places of precision, with a range of -10.00 to 10.00.

The way I'd prefer this to work is something like this:

While the user is typing in the Entry widget, pretty much anything is allowed, as long as it matches regex /^-?\d+\.?\d+$/

But as soon as the user leaves the Entry widget and it loses focus, any number that is out of range (< -10 or > 10) gets rejected, and numbers get formated to sprintf %.2f

My conundrum is that the Tk documentation goes to great pains to stress that you shouldn't use validation in an Entry widget to change the text variable. But that's exactly what I'm trying to do with it! If the user has typed a value that I consider out of range or invalid, I want to change it! How do I change it without changing it?

Here's some code to give an idea of how I'm floundering around with this. Please let me know what I should be doing here:

my $fctrEntry = $mw->Entry( -textvariable => \$factor, -validate => 'focus', -validatecommand => \&validate, #-invalidcommand => \&invalidate, -insertbackground => 'cyan', -selectforeground => 'white', -selectbackground => 'DarkRed', -highlightcolor => 'cyan', -background => 'black', -foreground => 'white')->grid( -row => $chartrow[2] + 2, -column => 32, -columnspan => 3, -sticky => 'new'); sub validate { my $val = shift; $val ||= "1.00"; if ($val !~ /^-?\d{1,2}\.\d\d$/ or $val < -10 or $val > 10) { print "Bad! "; return 0; } else { print "Good! "; return 1; } } sub invalidate { $factor = sprintf("%.2f", $_[0]); print "Validate! $factor "; }

In reply to Tk Entry validation conundrum by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.