Skip to content

Commit 5d5ee53

Browse files
ValidatedEntryBox: validate as the value changes (#273)
2 parents 5d44a0c + d8751af commit 5d5ee53

2 files changed

Lines changed: 41 additions & 2 deletions

File tree

‎Python_Engine/Python/src/python_toolkit/bhom_tkinter/widgets/validated_entry_box.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ def __init__(
3535
required: bool = True,
3636
custom_validator: Optional[Callable[[Any], tuple[bool, str]]] = None,
3737
on_validate: Optional[Callable[[bool], None]] = None,
38+
validate_on_change: bool = True,
3839
**kwargs
3940
) -> None:
4041
"""
@@ -56,6 +57,10 @@ def __init__(
5657
required: Whether the field is required
5758
custom_validator: Custom validation function that returns (is_valid, error_message)
5859
on_validate: Callback function called after validation with validation result
60+
validate_on_change: Validate as the user types, so a stale success mark is removed straight away
61+
and `on_validate` follows the value. Errors are not shown while typing, only on focus out
62+
and Return. If False, validation runs only on focus out and Return.
63+
An empty optional entry shows neither mark.
5964
"""
6065
super().__init__(parent, **kwargs)
6166

@@ -76,6 +81,7 @@ def __init__(
7681
self.required = required
7782
self.custom_validator = custom_validator
7883
self.on_validate = on_validate
84+
self.validate_on_change = validate_on_change
7985
self.default_value = default_value
8086

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

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

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

222233
# If not required and empty, it's valid
223234
if not self.required and not value_str:
224-
self._show_success()
235+
self.clear_error()
225236
self._call_validate_callback(True)
226237
base_result = (True, None, None)
227238
return self.apply_validation(base_result)

‎Python_Engine/Python/tests/test_bhom_tkinter_ui.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,34 @@ def fail_validator(_v):
291291
ok, msg, sev = custom_box.validate()
292292
assert ok is False and msg == "Custom failed"
293293

294+
# Validation runs as the value changes: an invalid value loses the success mark without focus out
295+
results = []
296+
live_box = ValidatedEntryBox(
297+
parent, value_type=float, min_value=100.0, max_value=500.0, required=False, on_validate=results.append
298+
)
299+
live_box.build()
300+
live_box.set("300")
301+
assert live_box.success_label.get() == "✓"
302+
# Partly typed / invalid values lose the tick but do not show an error while typing
303+
live_box.set("3")
304+
assert live_box.success_label.get().strip() == "" and live_box.error_label.get().strip() == ""
305+
assert results[-1] is False
306+
# The error shows once the user commits the value (focus out / Return)
307+
live_box.validate()
308+
assert live_box.error_label.get().startswith("Must be between")
309+
# Clearing an optional entry shows no marks and reports valid, so callers can re-enable Submit
310+
live_box.set("")
311+
assert live_box.success_label.get().strip() == "" and live_box.error_label.get().strip() == ""
312+
assert results[-1] is True
313+
live_box.validate()
314+
assert live_box.success_label.get().strip() == "" and results[-1] is True
315+
316+
# validate_on_change=False keeps the old behaviour: no mark until validate() is called
317+
lazy_box = ValidatedEntryBox(parent, value_type=float, required=False, validate_on_change=False)
318+
lazy_box.build()
319+
lazy_box.set("test")
320+
assert lazy_box.error_label.get().strip() == ""
321+
294322

295323
def test_rebuild():
296324
"""Verify that rebuild() re-places widgets and reflects mutations to self.widgets."""

0 commit comments

Comments
 (0)