Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def __init__(
required: bool = True,
custom_validator: Optional[Callable[[Any], tuple[bool, str]]] = None,
on_validate: Optional[Callable[[bool], None]] = None,
validate_on_change: bool = True,
**kwargs
) -> None:
"""
Expand All @@ -56,6 +57,10 @@ def __init__(
required: Whether the field is required
custom_validator: Custom validation function that returns (is_valid, error_message)
on_validate: Callback function called after validation with validation result
validate_on_change: Validate as the user types, so a stale success mark is removed straight away
and `on_validate` follows the value. Errors are not shown while typing, only on focus out
and Return. If False, validation runs only on focus out and Return.
An empty optional entry shows neither mark.
"""
super().__init__(parent, **kwargs)

Expand All @@ -76,6 +81,7 @@ def __init__(
self.required = required
self.custom_validator = custom_validator
self.on_validate = on_validate
self.validate_on_change = validate_on_change
self.default_value = default_value

# Store the external variable (any tkinter var type)
Expand Down Expand Up @@ -139,7 +145,12 @@ def __init__(
self.variable.trace_add("write", self._on_value_change)

def _on_value_change(self, *_) -> None:
"""Fire the on_change callback when the entry value changes."""
"""Validate (if enabled), then fire the on_change callback when the entry value changes."""
if self.validate_on_change:
is_valid = self.validate()[0]
if not is_valid:
# Keep the error for focus out / Return: the value may just be partly typed.
self.clear_error()
self._fire_on_change(self.get())

def _sync_to_external(self, *_) -> None:
Expand Down Expand Up @@ -221,7 +232,7 @@ def validate(self) -> tuple[bool, Optional[str], Optional[Literal['info', 'warni

# If not required and empty, it's valid
if not self.required and not value_str:
self._show_success()
self.clear_error()
self._call_validate_callback(True)
base_result = (True, None, None)
return self.apply_validation(base_result)
Expand Down
28 changes: 28 additions & 0 deletions Python_Engine/Python/tests/test_bhom_tkinter_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,34 @@ def fail_validator(_v):
ok, msg, sev = custom_box.validate()
assert ok is False and msg == "Custom failed"

# Validation runs as the value changes: an invalid value loses the success mark without focus out
results = []
live_box = ValidatedEntryBox(
parent, value_type=float, min_value=100.0, max_value=500.0, required=False, on_validate=results.append
)
live_box.build()
live_box.set("300")
assert live_box.success_label.get() == "✓"
# Partly typed / invalid values lose the tick but do not show an error while typing
live_box.set("3")
assert live_box.success_label.get().strip() == "" and live_box.error_label.get().strip() == ""
assert results[-1] is False
# The error shows once the user commits the value (focus out / Return)
live_box.validate()
assert live_box.error_label.get().startswith("Must be between")
# Clearing an optional entry shows no marks and reports valid, so callers can re-enable Submit
live_box.set("")
assert live_box.success_label.get().strip() == "" and live_box.error_label.get().strip() == ""
assert results[-1] is True
live_box.validate()
assert live_box.success_label.get().strip() == "" and results[-1] is True

# validate_on_change=False keeps the old behaviour: no mark until validate() is called
lazy_box = ValidatedEntryBox(parent, value_type=float, required=False, validate_on_change=False)
lazy_box.build()
lazy_box.set("test")
assert lazy_box.error_label.get().strip() == ""


def test_rebuild():
"""Verify that rebuild() re-places widgets and reflects mutations to self.widgets."""
Expand Down
Loading