How can I distinguish between "no input" and "invalid input" in a number Text Box?

In my use case, I’m using a number Text Box and want to validate the input. Both a valid number and an empty field (i.e. no entry) are acceptable. However, I’ve noticed that when I enter a non-numeric character, the Text Box still returns None—which is also what it returns when the field is left empty.

Is there a way to differentiate between an empty input and an invalid one (e.g. text or special characters) in this context?

The reason it returns None is because the underlying HTML input component when it has a type of “number” (which is what Anvil is doing in the background), it automatically refuses any non-numeric characters and doesn’t even show them in the input.

So the only validation you would have to do would be with numbers that use e for scientific notation that is invalid (which has a value of “” (a blank string)).

Tl;dr: you don’t need much validation, because the HTML component already does it automatically.

Thank you for your response. However, when using Firefox, I have no difficulties in entering characters even when the textbox is set to number mode.

A print statement of the text in the textbox returns “None” if an invalid character is entered, such as “d”. An empty textbox also returns “None”. Consequently, I am uncertain about the appropriate validation method for my specific use case.

Huh, I didn’t realize Firefox handled number inputs differently.

In that case, you can use this to make Firefox behave the same as Chromium browsers:

def text_box_1_change(self, **event_args):
    """This method is called when the text in this component is edited."""
    self.text_box_1.text = self.text_box_1.text or None

The only downside is that scientific notation is now blocked (except when pasting)

Of course, you could also run the one line in the function above at a more convenient time when the scientific notation has been properly entered (with the method above every keystroke triggers it)