跳转至

validation module

Validation framework for ttkbootstrap entry widgets.

This module provides classes and functions for adding validation to Entry, Spinbox, and Combobox widgets. When validation fails, a 'danger' colored border is applied to the widget, which disappears when the contents become valid.

The module includes
  • Predefined validation functions (text, numeric, phone number, regex, etc.)
  • Custom validation decorator (@validator)
  • Helper functions starting with "add_" prefix for quick validation setup

Classes:

Name Description
ValidationEvent

Contains attributes of a validation event from tkinter

Functions:

Name Description
add_validation

Core function to add validation to any compatible widget

add_text_validation

Validate that contents is alphabetic text

add_numeric_validation

Validate that contents is numeric

add_phonenumber_validation

Validate phone number format

add_regex_validation

Validate against custom regex pattern

add_range_validation

Validate numeric value is within range

add_option_validation

Validate value is in list of options

Example

Using predefined validation:

import ttkbootstrap as ttk
from ttkbootstrap.validation import *

app = ttk.Window()
entry = ttk.Entry()
entry.pack(padx=10, pady=10)

# Check if contents is text
add_text_validation(entry)

# Prevent any entry except text
add_text_validation(entry, when='key')

# Check for specific list of options
add_option_validation(entry, ['red', 'blue', 'green'])

# Validate against regex expression
add_regex_validation(entry, r'\d{4}-\d{2}-\d{2}')

app.mainloop()

Creating custom validation:

from ttkbootstrap.validation import validator, add_validation

@validator
def validate_long_text(event):
    if len(event.postchangetext) > 20:
        return True
    else:
        return False

# Apply custom validation
add_validation(entry, validate_long_text)

ValidationEvent

Contains the attributes of a validation event returned by the validatecommand on a tkinter widget.

Attributes:

actioncode (str):
    0 for an attempted deletion, 1 for an attempted insertion,
    or -1 if the callback was for focusin, focusout, or a
    change to the textvariable.

insertdeleteindex (str):
    When the user attempts to insert or delete text, this
    attribute will be the index of the beginning of the
    insertion or deletion. If the callback was due to focusin,
    focusout, or a change to the textvariable, the attribute
    will be -1.

postchangetext (str):
    The value that the text will have if the change is allowed.

prechangetext (str):
    The text in the entry before the change.

insertdeletetext (str):
    The text inserted or deleted if the call was due to an
    insertion or deletion.

validationtype (str):
    Specifies the widget's validation option which specifies
    _when_ the validation will occur.

validationreason (str):
    The reason for the validation callback (key, focusin,
    focusout, forced).

widget (Widget):
    The widget object that is being validated.
Source code in src/ttkbootstrap/validation.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class ValidationEvent:
    """Contains the attributes of a validation event returned by the
    `validatecommand` on a tkinter widget.

    Attributes:

        actioncode (str):
            0 for an attempted deletion, 1 for an attempted insertion,
            or -1 if the callback was for focusin, focusout, or a
            change to the textvariable.

        insertdeleteindex (str):
            When the user attempts to insert or delete text, this
            attribute will be the index of the beginning of the
            insertion or deletion. If the callback was due to focusin,
            focusout, or a change to the textvariable, the attribute
            will be -1.

        postchangetext (str):
            The value that the text will have if the change is allowed.

        prechangetext (str):
            The text in the entry before the change.

        insertdeletetext (str):
            The text inserted or deleted if the call was due to an
            insertion or deletion.

        validationtype (str):
            Specifies the widget's validation option which specifies
            _when_ the validation will occur.

        validationreason (str):
            The reason for the validation callback (key, focusin,
            focusout, forced).

        widget (Widget):
            The widget object that is being validated.
    """

    def __init__(self, d: str, i: str, P: str, s: str, S: str, v: str, V: str, W: str) -> None:
        self.actioncode = d
        self.insertdeleteindex = i
        self.postchangetext = P
        self.prechangetext = s
        self.insertdeletetext = S
        self.validationtype = v
        self.validationreason = V

        style = ttk.Style.get_instance()
        self.widget = style.master.nametowidget(
            W
        )  # replace with another method

add_numeric_validation(widget, when='focusout')

Check if widget contents is numeric. Sets the state to 'Invalid' if not a number.

Parameters:

widget (Widget):
    The widget on which to add validation.

when (str):
    Specifies when to apply validation. See the `add_validation`
    method docstring for a full list of options.
Source code in src/ttkbootstrap/validation.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def add_numeric_validation(widget: Misc, when: str = "focusout") -> None:
    """Check if widget contents is numeric. Sets the state to 'Invalid'
    if not a number.

    Parameters:

        widget (Widget):
            The widget on which to add validation.

        when (str):
            Specifies when to apply validation. See the `add_validation`
            method docstring for a full list of options.
    """
    add_validation(widget, _validate_number, when=when)

add_option_validation(widget, options, when='focusout')

Check if the widget contents is in a list of options.

Parameters:

widget (Widget):
    The widget on which to add validation.

when (str):
    Specifies when to apply validation. See the `add_validation`
    method docstring for a full list of options.
Source code in src/ttkbootstrap/validation.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def add_option_validation(widget: Misc, options: list[Any], when: str = "focusout") -> None:
    """Check if the widget contents is in a list of options.


    Parameters:

        widget (Widget):
            The widget on which to add validation.

        when (str):
            Specifies when to apply validation. See the `add_validation`
            method docstring for a full list of options.
    """
    add_validation(widget, _validate_options, options=options, when=when)

add_phonenumber_validation(widget, when='focusout')

Check if the widget contents matches a phone number pattern.

Parameters:

widget (Widget):
    The widget on which to add validation.

when (str):
    Specifies when to apply validation. See the `add_validation`
    method docstring for a full list of options.
Source code in src/ttkbootstrap/validation.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def add_phonenumber_validation(widget: Misc, when: str = "focusout") -> None:
    """Check if the widget contents matches a phone number pattern.

    Parameters:

        widget (Widget):
            The widget on which to add validation.

        when (str):
            Specifies when to apply validation. See the `add_validation`
            method docstring for a full list of options.
    """
    pattern = r"^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$"
    add_validation(widget, _validate_regex, pattern=pattern, when=when)

add_range_validation(widget, startrange, endrange, when='focusout')

Check if widget contents is within a range of numbers, inclusive. Sets the state to 'Invalid' if the number is outside of the range.

Parameters:

widget (Widget):
    The widget on which to add validation.

when (str):
    Specifies when to apply validation. See the `add_validation`
    method docstring for a full list of options.
Source code in src/ttkbootstrap/validation.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def add_range_validation(
    widget: Misc,
    startrange: Union[int, float],
    endrange: Union[int, float],
    when: str = "focusout",
) -> None:
    """Check if widget contents is within a range of numbers, inclusive.
    Sets the state to 'Invalid' if the number is outside of the range.

    Parameters:

        widget (Widget):
            The widget on which to add validation.

        when (str):
            Specifies when to apply validation. See the `add_validation`
            method docstring for a full list of options.
    """
    add_validation(
        widget,
        _validate_range,
        startrange=startrange,
        endrange=endrange,
        when=when,
    )

add_regex_validation(widget, pattern, when='focusout')

Check if widget contents matches regular expresssion. Sets the state to 'Invalid' if no match is found.

Parameters:

widget (Widget):
    The widget on which to add validation.

when (str):
    Specifies when to apply validation. See the `add_validation`
    method docstring for a full list of options.
Source code in src/ttkbootstrap/validation.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def add_regex_validation(widget: Misc, pattern: str, when: str = "focusout") -> None:
    """Check if widget contents matches regular expresssion. Sets the
    state to 'Invalid' if no match is found.

    Parameters:

        widget (Widget):
            The widget on which to add validation.

        when (str):
            Specifies when to apply validation. See the `add_validation`
            method docstring for a full list of options.
    """
    add_validation(widget, _validate_regex, pattern=pattern, when=when)

add_text_validation(widget, when='focusout')

Check if widget contents is alpha. Sets the state to 'Invalid' if not text.

Parameters:

widget (Widget):
    The widget on which to add validation.

when (str):
    Specifies when to apply validation. See the `add_validation`
    method docstring for a full list of options.
Source code in src/ttkbootstrap/validation.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def add_text_validation(widget: Misc, when: str = "focusout") -> None:
    """Check if widget contents is alpha. Sets the state to 'Invalid'
    if not text.

    Parameters:

        widget (Widget):
            The widget on which to add validation.

        when (str):
            Specifies when to apply validation. See the `add_validation`
            method docstring for a full list of options.
    """
    add_validation(widget, _validate_text, when=when)

add_validation(widget, func, when='focusout', **kwargs)

Adds validation to the widget of type Entry, Combobox, or Spinbox. The func should accept a parameter of type ValidationEvent and should return a boolean value.

Parameters:

widget (Widget):
    The widget on which validation will be applied.

func (Callable):
    The function that will be called when a validation event
    occurs.

when (str):
    Indicates when the validation event should occur. Possible
    values include:

    * focus - whenever the widget gets or loses focus
    * focusin - whenever the widget gets focus
    * focusout - whenever the widget loses focus
    * key - whenever a key is pressed
    * all - validate in all of the above situations

kwargs (Dict):
    Optional arguments passed to the callback.
Source code in src/ttkbootstrap/validation.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def add_validation(widget: Misc, func: Callable[..., bool], when: str = "focusout", **kwargs: Any) -> None:
    """Adds validation to the widget of type `Entry`, `Combobox`, or
    `Spinbox`. The func should accept a parameter of type
    `ValidationEvent` and should return a boolean value.

    Parameters:

        widget (Widget):
            The widget on which validation will be applied.

        func (Callable):
            The function that will be called when a validation event
            occurs.

        when (str):
            Indicates when the validation event should occur. Possible
            values include:

            * focus - whenever the widget gets or loses focus
            * focusin - whenever the widget gets focus
            * focusout - whenever the widget loses focus
            * key - whenever a key is pressed
            * all - validate in all of the above situations

        kwargs (Dict):
            Optional arguments passed to the callback.
    """
    f = widget.register(lambda *e: func(*e, **kwargs))
    subs = (r"%d", r"%i", r"%P", r"%s", r"%S", r"%v", r"%V", r"%W")
    widget.configure(validate=when, validatecommand=(f, *subs))

validator(func)

Decorates a standard function so that it receives the validation events returned by the validate command on the tkinter widgets.

Parameters:

func (Callable):
    The validation function to be decorated.
Source code in src/ttkbootstrap/validation.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def validator(func: Callable[[ValidationEvent], bool]) -> Callable[..., bool]:
    """Decorates a standard function so that it receives the validation
    events returned by the validate command on the tkinter widgets.

    Parameters:

        func (Callable):
            The validation function to be decorated.
    """

    def inner(*args: Any, **kw: Any) -> bool:
        event = ValidationEvent(*args)
        return func(event, **kw)

    return inner