I’m trying to update an input pending validation. If the validation fails it should revert to the old value. My code seems to work if I type slowly, but if I type a number like 300000 somewhat fast then the toast still works warning that it is invalid but the input remains at 300000. The text appears to update ok. Is there a bug or something I can do to make it work?
class ValidationErrorState(rx.State):
my_var: float = 0.0
_old_value: float = 0.0
def run_validation(self, value: str):
print("Value: ", value)
if float(value) > 100:
raise ValueError("Value must be less than 100")
def my_var_on_focus(self, value: str):
self._old_value = float(value)
def my_var_on_change(self, value: str):
try:
self.run_validation(value)
self.my_var = float(value)
except ValueError as e:
self.my_var = self._old_value
yield rx.toast(str(e))
@template(route="/error")
def validation_error():
return rx.card(
rx.vstack(
rx.debounce_input(
rx.input(
value=ValidationErrorState.my_var,
on_focus=lambda value: ValidationErrorState.my_var_on_focus(value),
on_change=lambda value: ValidationErrorState.my_var_on_change(value),
width="6rem",
size="1",
),
debounce_timeout=1000,
),
rx.text(ValidationErrorState.my_var.to(str)),
)
)