'Validation of Entry Widget in tkinter using python [duplicate]

I want to validate an entry widget in tkinter using python. I am expecting an input like 5.0e-7, 1.0e-5 so on. Please see the crude code.

class Validated(ttk.Entry):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.configure(
        validate='all',
        validatecommand=(self.register(self.validate), '%P'),
        )
  def validate(self, input, **kwargs):
    if any([(input not in '-1234567890e.')]):
      return True
    elif input is "":
      return True
    else:
      return False


Solution 1:[1]

Use regex:

import re

def is_valid(input_number):
    return bool(re.match(r"\d+.\d+e[-+]\d+", input_number))

input_number = "5.0e-8"
valid = is_valid(input_number)
print(valid)  # returns True
input_number = "5.0ae-8"
valid = is_valid(input_number)
print(valid)  # returns False

Explanation of regex \d+.\d+e[-+]\d+: \d matches one digit, \d+ matches any number of digits, [-+] matches + or -, . and e are hardcoded. You can also test your regular expression here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman