IntegerInput
to restrict typing only numbers?
#2291
Replies: 3 comments 4 replies
-
I did something similar for one of my apps last year: https://github.com/davep/unbored/blob/main/unbored/filter_input.py |
Beta Was this translation helpful? Give feedback.
-
We do need an answer to this. There should be some way of restricting valid characters on an Input, and a dedicated IntegerInput. I also want to add some kind of validator framework that works accross objects. |
Beta Was this translation helpful? Give feedback.
-
Here's my solution, a class ValidatedInput(Widget):
DEFAULT_CSS = """
ValidatedInput {
height: auto;
}
ValidatedInput > Input.error {
border: tall $error;
}
ValidatedInput > Label {
height: 1;
padding: 0 0 0 1;
color: $text-muted;
}
ValidatedInput > Label.error {
color: $error
}
"""
class Changed(Message):
def __init__(self, input: ValidatedInput, value: str) -> None:
super().__init__()
self.input = input
self.value = value
def __init__(
self,
validate: Callable[[str], str | None],
value: str | None = None,
prompt: str | None = None,
id: str | None = None,
) -> None:
super().__init__(id=id)
self.validate = validate
self.initial_value = value
self.prompt = prompt or ""
def compose(self) -> ComposeResult:
yield Input(value=self.initial_value)
yield Label(self.prompt)
def on_input_changed(self, event: Input.Changed) -> None:
message = self.validate(event.value)
label = self.query_one(Label)
event.input.set_class(message is not None, "error")
label.set_class(message is not None, "error")
if message is not None:
self.query_one(Label).set_class(True, "error").update(message)
else:
self.query_one(Label).set_class(False, "error").update(self.prompt)
self.post_message(self.Changed(self, event.value)) Example: import portion as P
def validate_price(value: str) -> str | None:
return (
None
if value.isdecimal() and int(value) in P.closedopen(1, P.inf)
else "Price must be a positive integer."
)
yield ValidatedInput(
validate=validate_price,
value=str(100),
id="price",
) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Sometimes you might want to restrict an
Input
to only allow typing numbers. This saves having to validate that the submitted value is a number and then implementing some feedback to the user if invalid. Here's my quick implementation:Beta Was this translation helpful? Give feedback.
All reactions