In the previous example program, we wanted the program user to type numbers, not arbitrary strings. That is, the user is allowed to enter only digits
9 and a hyphen (
-). The hyphen, if present at all, must be the first symbol of the input string.
On the surface, this input validation task sounds simple. We can install a key listener to the text field and consume all key events that aren’t digits or a hyphen. Unfortunately, this simple approach, although commonly recommended as a method for input validation, does not work well in practice. First, not every combination of the valid input characters is a valid number. For example,
3-3 aren’t valid, even though they are made up from valid input characters. ...