Forms
This example showcases a validated signup form combining webcompy.forms state management (use_field, use_form, built-in and custom validators) with accessible themed controls from webcompy.ui.
Use this pattern for multi-field workflows requiring blur-gated error display, ARIA descriptions, collective validation on submit, and clean reset behavior.
Forms
Demo
Code
"""Standalone docs demo: a complete form built from ui form controls."""
from typing import Any
from webcompy.app import WebComPyApp
from webcompy.components import ComponentContext, define_component
from webcompy.elements import html
from webcompy.forms import email, min_length, required, use_field, use_form
from webcompy.signal import use_computed, use_state
from webcompy.ui import Checkbox, FormField, Input, RadioGroup, Select, Switch, Textarea
@define_component("ui-form-controls-demo-app")
def UiFormControlsDemo(_: ComponentContext[None]) -> Any:
name_field = use_field(
use_state(lambda: ""), validators=[required(), min_length(3, "At least 3 characters")], name="name"
)
email_field = use_field(use_state(lambda: ""), validators=[required(), email()], name="email")
country_field = use_field(use_state(lambda: ""), validators=[required()], name="country")
notes_field = use_field(use_state(lambda: ""), name="notes")
updates_field = use_field(use_state(lambda: True), name="updates")
marketing_field = use_field(use_state(lambda: False), name="marketing")
plan_field = use_field(use_state(lambda: "free"), validators=[required()], name="plan")
agree_field = use_field(
use_state(lambda: False), validators=[lambda v: None if v else "Please accept the terms"], name="agree"
)
form = use_form(
name=name_field,
email=email_field,
country=country_field,
plan=plan_field,
agree=agree_field,
)
submitted = use_state(lambda: "")
def _on_submit(values: dict[str, Any]) -> None:
submitted.value = f"Welcome, {values['name']} ({values['plan']} plan)!"
def _on_reset(_ev: Any) -> None:
form.reset()
submitted.value = ""
return html.DIV(
{"class": "ufc-demo"},
html.H1({}, "UI Form Controls Demo"),
html.P({}, "Themed form controls with Field binding, validation on blur, and accessible error wiring."),
html.FORM(
{"@submit": form.submit(_on_submit)},
FormField(
{"field": name_field, "label": "Name"},
slots={"default": lambda: Input({"field": name_field, "placeholder": "Your name"})},
),
FormField(
{"field": email_field, "label": "Email"},
slots={
"default": lambda: Input(
{"field": email_field, "input_type": "email", "placeholder": "[email protected]"}
)
},
),
FormField(
{"field": country_field, "label": "Country"},
slots={
"default": lambda: Select(
{
"field": country_field,
"options": [
{"value": "", "label": "Choose your country…"},
{"value": "jp", "label": "Japan"},
{"value": "us", "label": "United States"},
{"value": "de", "label": "Germany"},
],
}
)
},
),
FormField(
{"field": notes_field, "label": "Notes"},
slots={"default": lambda: Textarea({"field": notes_field, "rows": 3, "placeholder": "Anything else?"})},
),
FormField(
{"field": plan_field},
slots={
"default": lambda: RadioGroup(
{
"field": plan_field,
"legend": "Plan",
"options": [
{"value": "free", "label": "Free"},
{"value": "pro", "label": "Pro"},
{"value": "team", "label": "Team"},
],
}
)
},
),
html.DIV(
{"class": "ufc-demo-toggles"},
FormField(
{"field": agree_field, "label": "I accept the terms"},
slots={"default": lambda: Checkbox({"field": agree_field})},
),
Switch({"field": updates_field, "label": "Product updates"}),
Switch({"field": marketing_field, "label": "Marketing emails"}),
),
html.DIV(
{"class": "ufc-demo-actions"},
html.BUTTON({"type": "submit", "id": "ufc-demo-submit"}, "Submit"),
html.BUTTON({"type": "button", "id": "ufc-demo-reset", "@click": _on_reset}, "Reset"),
),
),
html.P({"id": "ufc-demo-status"}, use_computed(lambda: submitted.value)),
)
UiFormControlsDemo.scoped_style = {
".ufc-demo": {
"font-family": "var(--font-sans)",
"color": "var(--color-fg)",
"padding": "var(--space-4)",
"max-width": "28rem",
},
".ufc-demo form": {
"display": "flex",
"flex-direction": "column",
"gap": "0.75rem",
},
".ufc-demo-toggles": {
"display": "flex",
"flex-wrap": "wrap",
"gap": "1rem",
"align-items": "center",
},
".ufc-demo-actions": {
"display": "flex",
"gap": "0.5rem",
"margin-top": "0.5rem",
},
".ufc-demo-actions button": {
"padding": "0.5rem 1rem",
"border": "1px solid var(--color-border)",
"border-radius": "var(--radius-sm)",
"background": "var(--color-bg-elevated)",
"color": "var(--color-fg)",
"cursor": "pointer",
},
"#ufc-demo-submit": {
"background": "var(--color-accent)",
"border-color": "var(--color-accent)",
"color": "var(--color-on-accent)",
},
"#ufc-demo-status": {
"margin-top": "0.75rem",
"font-weight": "600",
"color": "var(--color-success)",
},
}
app = WebComPyApp(root_component=UiFormControlsDemo)
app.run()What this demonstrates#
- Reactive fields and validators: Each
use_field(use_state(...), validators=[...])tracksvalue,touched,dirty, anderrorsautomatically while built-inrequired(),min_length(),email(), and custom lambdas validate live as the user edits. - Accessible
FormFieldwiring:FormFieldinjects DI-scoped association IDs into its slotted control (Input,Select,Textarea,Checkbox,RadioGroup), togglingaria-invalid,aria-describedby, anddata-state="invalid"only after a field is touched or the form submits. - Independent switches alongside validated fields:
Switchbinds standalone preference booleans (updates_field,marketing_field) via:bindeven when they do not carry validation rules. - Submit & reset orchestration:
form.submit(handler)prevents default form submission, touches all registered fields, aborts on validation errors, or passes a typed snapshot dictionary to_on_submit(values);form.reset()clears touched/dirty flags and restores defaults.
Key mechanisms and how to adapt#
- Async submissions: Change
_on_submittoasync def _on_submit(values)and bind"disabled": form.submittingon the submit button to prevent double submits while awaitingHttpClient.post(...). - Custom styling with headless controls: Import controls from
webcompy.ui.headlessinstead ofwebcompy.uiwhen applying a custom design system while retaining keyboard,data-state, and ARIA semantics. - Custom cross-field rules: Check relationships across
form.values()inside_on_submitor compute derived warnings withuse_computed(...).
Next steps#
- Learn validator APIs and
:bindrules in Forms. - Inspect headless vs. themed contracts and DI slot association IDs in UI Headless Contract and UI Primitives.
- Wire form submission through a mocked or real HTTP endpoint in Fetch Middleware.