"Tips and Tricks" section of the first post, chapter
Let entry accept (some) numbers only:
Actually it's an interesting example and shows the dilemma when dealing with incorrect input. If an entry widget is supposed to accept only numbers and the user inputs letters, what should the checking routine do?
- Erase everything and replace with zero? That's probably the worst reaction
- Erase everything? Very common and not bad.
- Keep wrong entry and alert user? That's what I would prefer and what most web forms are doing.
This dilemma could be avoided if the entry would do what the headline promises and would accept numbers only - nothing else. Any input of non-numbers should be blocked. No more rubbish input to clean up later. Can it be done?
Of course it can. Here is the code:
Code: Select all
#!/bin/bash
TMP=/tmp/last_good # file to hold last verified (=good) entry value
echo > $TMP # create file
trap "rm $TMP" EXIT # delete tmp file before closing dialog
echo '
<vbox>
<text label="Strict number entry (non-numbers rejected)"></text>
<entry>
<variable>vENTRY</variable>
<input file>'$TMP'</input>
<action condition="command_is_true([[ $vENTRY =~ ^[0-9]*$ ]] && echo $vENTRY > '$TMP' || { beep & echo true;})">refresh:vENTRY</action>
</entry>
<button></button>
</vbox>' |gtkdialog -cs
The code checks every new input. If it's good, i.e if the entry field still contains only numbers, the content is saved to the tmp file. If the user has entered a non-number, he is alerted with a beep and the entry field is refreshed with the content of the tmp file (holding the field content displayed before the non-number was added). Simply speaking it's an automatic undo function.
Important: The tmp file must not be completely empty. Apparently gtkdialog <input file> ignores empty files. That's the reason for the
echo > $TMP command, which creates the file by sending a newline character.
This real-time checking method can be useful for many things, i.e it can be used to change capitalization on-the-fly and it can be used to support the final checking. I'm still exploring the possibilities.