Excluding 'e' input from Textbox set to number

What I’m trying to do:
Does anyone know how to exclude the letter “e” from being entered in a textbox when the type is set to number? If statements to exclude it causes a TypeError.

What I’ve tried and what’s not working:

def text_box_user_score_change(self, **event_args):
if self.text_box_user_score.text is not None:
if not isinstance(self.text_box_user_score.text, int) or self.text_box_user_score.text < 0 or self.text_box_user_score.text > 100:
self.text_box_user_score.text = None

Any try/except statement or if statements I use to exclude ‘e’ as a response causes TypeError. Thanks for help.

I haven’t tried, but I think that this should be or int(self.text_box_user_score.text) > 100

The problem with what you are trying to do is that the user will see the text disappearing while they are typing. For example they type 123e and everything goes away.

Intercepting the last character typed and removing only that one is possible, but not easy, because one could type the e in the middle of a long number. In javascript you can intercept the keyboard events and prevent them from reaching the textbox, but I think it’s overkilling. Plus it often doesn’t feel right for the user.

I usually use the Validator dependency which will take care of showing an error message if the input is wrong.

Thanks for the response. The problem is Anvil accepts “e” as an input when textbox is set to number. I’m guessing because it could be used as Euler’s number. I don’t know that for sure. Nevertheless, I need to limit the textbox inputs to int 0-100. I just can not figure out a straightforward way to prevent “e” input.

Very likely e is allowed for entering exponential notation, like 5e1 (which is 50, which is a valid integer between 0 and 100).

The main reason why you set a textbox to number is to show the numerical keypad on mobile devices, not to make sure the user enters the correct value.

If you validate the input instead of the keystrokes, you can get the same result, with the added benefit of showing a message to the users so they understand what they did wrong.

If I press a key and nothing happens, I may think there is something wrong with the keyboard or with the app.

If I press a key and I see a message that says “You pressed the wrong key, you should instead press the other key”, I know what I did wrong.

With the Validator all you need to do is add these 3 lines and they take care of showing the popup with the error message:

self.validator = Validator(default_placement='right', default_events=['change'])
self.validator.between(self.text_box_user_score,  min_value=0, max_value=100, include_min=True, include_max=True)
self.validator.integer(self.text_box_user_score)
2 Likes

Great explanation. That solved my problem. Thank you for the help!

1 Like