how to validate text fields so that it only accepts numbers, python flet

464 Views Asked by At

I am trying to validate a text field so that it only accepts numbers when the user writes with the keyboard, but I can't think of how to do it.

example of a text field that I want to be only numeric:

self.cedula = TextField(label="Cedula", hint_text="Ingresar Cedula", border_radius=30, border_color="#820000", width=300, height=60)

Edit: I found out how to know if the user writes a number or a letter, now my problem is the following

I want everything that is not a number to be eliminated in the else, but I can't find a way, declare the field value to be empty but the entire field is emptied

I attached the function

def validarNumeros(self, campo, pagee):
    campo = campo
    pagee = pagee

    digitos = campo.value

    if digitos.isdigit():
        print("numero")
    else:
        print("letra")
        self.cedula.value = ""
        pagee.update()
2

There are 2 best solutions below

0
On BEST ANSWER

Maybe this can help and I'm starting with Flet. I have taken your function and combined it with the on_change event in such a way that using exceptions does not allow entering anything that is not a number or a single decimal point. Additionally, if something wrong is entered, the numbers already entered and previously validated are not lost. I hope it helps you,

import flet
from flet import Page,TextField

last_valid_value = ""

def validate_numbers(field, pagee):
    global last_valid_value
    digits = field.value
    if digits == "":
        last_valid_value = ""
    else:
        try:
            float(digits.replace(",", ""))
            last_valid_value = digits
        except ValueError:
            field.value = last_valid_value
            pagee.update()

def main(page: Page):
    amount = TextField(label="Amount", height=37, on_change=lambda e: validate_numbers(amount, page))
    page.add(amount)

flet.app(target=main)
0
On

you can use input_filter argument in flet.TextField, input_filter take flet.InputFilter that allow you to use a simple regex to filter input. the regex here is "from start, only accept numbers zero or more times". on_change event is not called if filter no satisfied:

import flet


def main(page: flet.Page):
    def on_text_change(event):
        print(event.data)
    _filter = flet.InputFilter('^[0-9]*')
    textfield = flet.TextField(input_filter=_filter,on_change=on_text_change,autofocus=True)
    page.add(textfield)


flet.app(main)

i hope it may help you, sorry for my bad english.