Hooks & Validation¶
ButtonValidator Class¶
Configurable button validator with built-in and custom rules.
Constructor¶
| Parameter | Type | Default | Description |
|---|---|---|---|
include_defaults | bool | True | Include default validation rules (text length, callback data checks) |
add_rule method¶
Add a custom validation rule.
| Parameter | Type | Description |
|---|---|---|
rule | Callable[[Any], str \| None] | Returns None if valid, error message if invalid |
Returns: ButtonValidator (chainable)
Usage
validate_button method¶
Validate a single button against all registered rules.
Returns: dict[str, Any]
| Key | Type | Description |
|---|---|---|
is_valid | bool | Whether the button passed all rules |
errors | list[str] | Error messages from failed rules |
checked_rules | int | Number of rules checked |
Usage
KeyboardHookManager Class¶
Manages hooks for keyboard construction lifecycle.
Hook Types¶
| Method | Hook Signature | When it Runs |
|---|---|---|
add_button_hook(hook) | (button) → button | Each button during construction |
add_pre_hook(hook) | (keyboard) → None | Before construction |
add_post_hook(hook) | (keyboard) → None | After construction |
add_error_hook(hook) | (exception, keyboard) → None | When a hook raises |
All methods return KeyboardHookManager for chaining.
process_button method¶
Process a button through all button hooks.
execute_pre_hooks / execute_post_hooks method¶
Execute all pre/post-construction hooks.
Full Example
from pykeyboard import KeyboardHookManager
manager = KeyboardHookManager()
# Uppercase all button text
manager.add_button_hook(
lambda btn: setattr(btn, "text", btn.text.upper()) or btn
)
# Log keyboard construction
manager.add_post_hook(
lambda kb: print(f"Built keyboard with {len(kb.keyboard)} rows")
)
Convenience Functions¶
validate_button function¶
Quick-validate a button with default rules.
from pykeyboard import validate_button, InlineButton
is_valid = validate_button(InlineButton("OK", "ok")) # True
validate_keyboard function¶
Validate all buttons in a keyboard.
Returns: dict[str, Any]
| Key | Type | Description |
|---|---|---|
is_valid | bool | All buttons valid |
total_buttons | int | Total buttons checked |
valid_buttons | int | Buttons that passed |
invalid_buttons | int | Buttons that failed |
errors | list | Detailed error info |