Forms¶
Bindings, validation, an aggregated submit handler, and accessible error messages. The form helpers live in wybthon.forms.
from wybthon import Show, component, html, render
from wybthon.forms import (
a11y_control_attrs,
bind_checkbox,
bind_select,
bind_text,
email,
error_message_attrs,
form_state,
min_length,
on_submit_validated,
required,
)
@component
def SignupForm():
fields = form_state({"name": "", "email": "", "plan": "free", "subscribe": False})
rules = {
"name": [required(), min_length(2)],
"email": [required(), email()],
}
def save(f):
print({k: field.value.peek() for k, field in f.items()})
name = fields["name"]
mail = fields["email"]
plan = fields["plan"]
subscribe = fields["subscribe"]
return html(t"""
<form onsubmit={on_submit_validated(rules, save, fields)}>
<p>
<label for="name">Name</label>
<input
id="name"
{bind_text(name, validators=rules["name"])}
{a11y_control_attrs(name, described_by_id="name-err")}
>
<span {error_message_attrs(id="name-err")}>{name.error()}</span>
</p>
<p>
<label for="email">Email</label>
<input
id="email"
type="email"
{bind_text(mail, validators=rules["email"])}
{a11y_control_attrs(mail, described_by_id="email-err")}
>
<span {error_message_attrs(id="email-err")}>{mail.error()}</span>
</p>
<p>
<label for="plan">Plan</label>
<select id="plan" {bind_select(plan)}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</p>
<p>
<label><input type="checkbox" {bind_checkbox(subscribe)}> Subscribe to the newsletter</label>
</p>
{Show(plan.value() == "pro", html(t"<p>Pro plans are billed monthly.</p>"))}
<button type="submit">Sign up</button>
</form>
""")
render(SignupForm(), "#app")
How it works¶
form_statereturns a dict ofFieldobjects. Each field carriesvalue,error, andtouchedaccessors with matching setters, so every piece of form state is a signal.bind_textreturns{"value": field.value, "on_input": handler}. Thevalueentry is the accessor itself, so programmatic writes throughfield.set_value(...)update the input too. Validators run on everyinputevent.{bind_text(...)}in the<input>tag is a spread: the mapping's entries are applied as props. A spread is evaluated once, when the template is created; the accessors inside it (the value, the ARIA state) are what keep the input in sync. A tag can take several spreads alongside ordinary attributes. Spread keys use Python names (on_input,aria_invalid), the same nameshprops take.<span ...>{name.error()}</span>reads the error in the template, so the message appears and disappears as validation runs.a11y_control_attrsproduces reactivearia-invalidandaria-describedbyprops;error_message_attrsmarks the message container as a polite live region.on_submit_validatedcallsprevent_default(), validates every field inrules(marking them touched), and only invokessavewhen all pass. Useon_submitwhen you want to handle validation yourself.- A
Fieldis a container of accessors, not an accessor itself, so the condition readsplan.value(). The compiler passesShowa getter forplan.value() == "pro", andShowmounts the note only while it's true. - Static attributes such as
for="name"andtype="email"are written into the compiled template, so they cost nothing per instance.
Schema-driven rules¶
rules_from_schema builds the validators map from a small declarative schema:
from wybthon.forms import rules_from_schema
rules = rules_from_schema(
{
"name": {"required": True, "min_length": 2},
"email": {"required": "Email is required", "email": True},
}
)
Validating on demand¶
Call validate_form to validate everything and get an (is_valid, errors) tuple, or validate_field for one field:
from wybthon.forms import validate_field, validate_form
ok, errors = validate_form(fields, rules)
validate_field(fields["name"], rules["name"])