Search code examples
pythonvalidationframeworkstextfieldflet

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


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()

Solution

  • 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)