Text Box Numeric Entry Best Practice

I have a text box which requires a non-negative integer entry. I can limit the text box to numeric easily enough with the number type, but I need to test for integer and non-negativity. I am doing this in the Pressed-Enter event. The problem (as I discovered) is that (despite instructions to Press Enter in a form label) people on phones don’t want to press enter. (A few claimed to have no idea what “enter” even means on a phone.)

The way I would normally do this it to trap everything but numbers (and BackSpace) in the KeyPress event, but that event doesn’t exist in Anvil Textboxes, right?

One idea I had was to add the logic to the Lost Focus event as well and then return focus to the text box on failure with a warning. But I’m wondering whether there is some best practice here.

In HTML you can set a min and max attribute for the input tag when the type is number. It’d be nice if Anvil exposed those…might be worth a feature request. Then you could set a min of 1 and be ensured you’d have no negative numbers.

With Anvil as is, you might look at the Anvil Augments dependency which allows adding non-standard events to components. Then you could have a key press event. AnvilAugment: Hover, Focus, Key Bindings Dependency

3 Likes

I would just use the change even on the text box:

  def text_box_1_change(self, **event_args):
    if self.text_box_1.text is not None:
      if not isinstance(self.text_box_1.text, int) or self.text_box_1.text < 0:
        self.text_box_1.text = None

for type, I selected number:
image

On mobile this seems to open up a numerical pad instead of a keyboard.

1 Like

Thanks, @ianbuywise. I had just made the change to a number field without republishing and I hadn’t noticed that on mobile it brings up a number pad. That solves the problem, I think. But I need to see how the users take it. (Thanks to @jshaffstall as well. I’ve been meaning to look into AnvilAugment, and this could be the chance.)

The augment library is now also part of Anvil Extras

2 Likes