Resident validating data entry
Data Validation within apps and business forms is critical to prevent errors, and to ensure data transactions occur without errors and uncomfortable bottlenecks during submission.In this blog I will be sharing my personal best practices for data validation in the Power Apps that I design.sv.trace('w', lambda nm, idx, mode, var=sv: validate_float(var)) ent = Entry(root, textvariable=sv) ent.pack() root.mainloop() from tkinter import * root = Tk() def test Val(in Str,acttyp): if acttyp == '1': #insert if not in Str.isdigit(): return False return True entry = Entry(root, validate="key") entry['validatecommand'] = (entry.register(test Val),'%P','%d') entry.pack() root.mainloop() While studying Bryan Oakley's answer, something told me that a far more general solution could be developed.The following example introduces a mode enumeration, a type dictionary, and a setup function for validation purposes.
The validate method simply tries to convert the value to an object of the right kind, and returns None (reject) if that fails.
Hence, we can differentiate between a deletion by itself and a deletion directly followed by an insertion due to a substitution because the latter has no idle time between deletion and insertion.
This is exploited using a substitution Flag and a class Validated Entry(Entry): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) Validate = (self.register(self.validate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') # attach the registered validation function to this spinbox self.config(validate = "all", validatecommand = Validate) def validate(self, type, index, result, prior, indel Text, current Validation Mode, reason, widget Name): if type Of Action == "0": # set a flag that can be checked by the insertion validation for being part of the substitution self.substitution Flag = True # store desired data self.prior Before Deletion = prior self.index Before Deletion = index # reset the flag after idle self.after_idle(lambda: setattr(self, "substitution Flag", False)) # normal deletion validation pass elif type Of Action == "1": # if this is a substitution, everything is shifted left by a deletion, so undo this by using the previous prior if self.substitution Flag: # restore desired data to what it was during validation of the deletion prior = self.prior Before Deletion index = self.index Before Deletion # optional (often not required) additional behavior upon substitution pass else: # normal insertion validation pass return True import tkinter # imports Tkinter module root = tkinter.
Therefore, I spend some effort checking all my business apps for proper data validation.
Questions you may want to use to challenge the effectiveness of your own forms include: By running through these simple questions above, you'll be able to make a list of form enhancement targets.