Inline Validation
Demonstrates how to do inline field validation
import time
from fasthtml.common import H3, Button, Div, Form, Img, Input, Label, NotStr, Span, Style, fast_app
css = """
.error input {
box-shadow: 0 0 3px #CC0000;
}
.valid input {
box-shadow: 0 0 3px #36cc00;
}
"""
app, rt = fast_app(hdrs=[Style(css)])
@app.get
def page():
return Div(cls="container")(
H3("Signup Form"),
NotStr("Enter an email and on tab out it will be validated. Only <ins>test@test.com</ins> will pass."),
Form(
make_email_field("", error=False, touched=False),
Div(Label("Name"), Input(name="name")),
Button("Submit", disabled="", cls="btn primary"),
),
)
@app.post("/contact/email")
def validate_email(email: str):
time.sleep(1)
return make_email_field(email, email != "test@test.com", True)
def make_email_field(value: str, error: bool, touched: bool):
cls = "" if not touched else "error" if error else "valid"
return Div(hx_target="this", hx_swap="outerHTML", cls=cls)(
Label("Email"),
Input(name="email", hx_post=validate_email, hx_indicator="#ind", value=value),
Img(id="ind", src="/img/bars.svg", cls="htmx-indicator"),
Span("Please enter a valid email address", style="color:red;") if error else None,
)