How to show errors in form? #495
Replies: 1 comment 2 replies
-
I did inline validation using HTMX, based on this reference. Here are some helper components. The # src/components/input.py
def LabelErrorInput(label, id, value=None, placeholder="", type="text", **kwargs):
return Div(cls="space-y-2", hx_target=f"#{id}-error", hx_swap="innerHTML")(
LabelInput(label, id=id, value=value, placeholder=placeholder, type=type, **kwargs),
Div(id=f"{id}-error"),
)
def ErrorText(c):
return P(c, cls=(TextT.small, TextT.danger)) Here are the login form and its page. # src/login.py
from .components.input import ErrorText, LabelErrorInput
login_form = UkFormSection(
"Login",
"Enter your email and password to log in.",
LabelErrorInput(
"Email",
"email",
required=True,
type="email",
hx_post="/login/email",
),
LabelErrorInput(
"Password",
"password",
required=True,
type="password",
hx_post="/login/password",
),
button_txt="Log in",
)
@app.get("/login")
def login_get(session):
if session.get("auth", False):
return RedirectResponse("/", status_code=303)
return (
Title("Login"),
Div(
Section(
DivVStacked(
Card(
Form(action="/login", method="post")(login_form),
cls="w-full md:w-1/2 lg:w-100",
)
)
),
cls="p-4",
),
) Here are the input validation endpoints. They are called each time your respective input changes, and each function gets all of the form data ( # src/login.py
from dataclasses import dataclass
from email_validator import validate_email, EmailNotValidError
@dataclass
class Login:
email: str
password: str
@app.post("/login/email")
def login_email_post(login: Login):
if not login.email:
return ErrorText("Enter an email!")
try:
validate_email(login.email, check_deliverability=False)
except EmailNotValidError as e:
return ErrorText(str(e))
@app.post("/login/password")
def login_password_post(login: Login):
if not login.password:
return ErrorText("Enter a password!") For completeness, here is the form POST endpoint (some code was removed). Inputs should be validated again to keep it safe. # src/login.py
@app.post("/login")
def login_post(login: Login, session):
# validate inputs again before continuing
# check email / password
if not valid_login:
add_toast(session, "Invalid email or password", "error")
return RedirectResponse("/login", status_code=303)
session["auth"] = True
session["user"] = json.dumps(...)
redir_url = session.get("redir_url", "/")
if "redir_url" in session:
del session["redir_url"]
return RedirectResponse(redir_url, status_code=303) The undefined classes come from either |
Beta Was this translation helpful? Give feedback.
-
Hey, what's the right way to show form errors in FastHTML?
For example, I have form with two fields: an integer and a string.
The form should show error if a person enters a string in the integer field. How do we do this?
I tried this code below.
If I put a string in the
id
field, it returns an error 500. I want to show the error in this case that theid
was not integer. Also render the form again with the user's values.Beta Was this translation helpful? Give feedback.
All reactions