Search code examples
pythonvalidationtkinter

How to allow dot input for the 'key' validation


I'm trying to add validation to the entry box (tkinter) for the ip address input. It should only allow 0 - 255 inputs seperated by four dots. but the code which i have does not allow dots in the entry box. Someone help!

import tkinter as tk

def validate_ip( value_if_allowed, validation_type):
    if validation_type == 'key':
        try:
            if value_if_allowed:
                parts = value_if_allowed.split('.')
                if len(parts) <= 4:
                    for part in parts:
                        if not (0 <= int(part) <= 255):
                            return False
                else:
                    return False
        except ValueError:
            return False
    return True

root = tk.Tk()
root.title("IP Address Validation")

validate_ip_entry = root.register(validate_ip)
ip_entry = tk.Entry(root, validate="key", validatecommand=(validate_ip_entry,  '%P',   '%v'))
ip_entry.pack(padx=10, pady=10)

root.mainloop()

It is currently allowing numbers only till 255 but not allowing me to enter dots after that.


Solution

  • You could wrap int(part) in try/except and remove empty parts:

    def validate_ip(value_if_allowed, validation_type):
        if validation_type == 'key':
            for part in value_if_allowed.split('.'):
                # ignore empty string from split!
                if not part:
                    continue
    
                # silently convert part to int.
                try:
                    part = int(part)
                except ValueError:
                    return False
    
                if not (0 <= int(part) <= 255):
                    return False
            return True