2. Check the current draft without losing it
Validation is a small pure function. It returns the first field that needs correcting and does not mutate the draft. The email check catches missing address parts, extra @ signs and whitespace; it is deliberately not a complete email-address parser or proof that the address exists.
Keep only one additional retained value: whether the customer has asked for a check. After that first attempt, derive the result from the current fields on every build. This avoids a subtle bug in forms that store a submitted flag: someone can change a previously valid field while the screen continues to claim that the form is ready.
Here the fields remain editable after a successful check. The check button never submits anything, and the feedback says so. In a connected application, submit through an effect, retain a loading state and handle success and failure explicitly. The server must repeat validation before accepting the request.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/validation.rs","value":"src-validation-rs"},{"index":1,"label":"src/app.rs","value":"src-app-rs"},{"index":2,"label":"src/lib.rs","value":"src-lib-rs"},{"index":3,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/validation.rs","value":"src-validation-rs"}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Field {
Name,
Email,
Subject,
Message,
}
impl Field {
pub fn error_key(self) -> &'static str {
match self {
Self::Name => "contact.error.name",
Self::Email => "contact.error.email",
Self::Subject => "contact.error.subject",
Self::Message => "contact.error.message",
}
}
}
pub fn validate(name: &str, email: &str, subject: &str, message: &str) -> Result<(), Field> {
if name.trim().is_empty() {
return Err(Field::Name);
}
// A useful form check, not a complete email-address parser.
let email = email.trim();
let valid_email = email.split_once('@').is_some_and(|(local, domain)| {
!local.is_empty() && !domain.is_empty() && !domain.contains('@')
}) && !email.chars().any(char::is_whitespace);
if !valid_email {
return Err(Field::Email);
}
if subject.trim().is_empty() || subject.chars().count() > 120 {
return Err(Field::Subject);
}
if message.trim().is_empty() || message.chars().count() > 2000 {
return Err(Field::Message);
}
Ok(())
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::validation::{validate, Field};
fission_component! {
pub ContactForm<()> {
state {
name: String = String::new(),
email: String = String::new(),
subject: String = String::new(),
message: String = String::new(),
checked: bool = false,
}
}
view(form, _state, cx) {
let tokens = &cx.view.env().theme.tokens;
let error = if form.checked {
validate(&form.name, &form.email, &form.subject, &form.message).err()
} else {
None
};
let name_error = (error == Some(Field::Name)).then(|| cx.tr(Field::Name.error_key()));
let email_error = (error == Some(Field::Email)).then(|| cx.tr(Field::Email.error_key()));
let subject_error = (error == Some(Field::Subject)).then(|| cx.tr(Field::Subject.error_key()));
let message_error = (error == Some(Field::Message)).then(|| cx.tr(Field::Message.error_key()));
} =>
Container(
Scroll(
id: Some(WidgetId::explicit("harbour-contact-scroll")),
semantic_label: Some(cx.tr("contact.form.semantics")),
child: Container(Column(gap: tokens.spacing.m, children: [
Text(cx.tr("contact.form.title"))
.weight(tokens.typography.font_weight_bold),
Text(cx.tr("contact.form.detail"))
.color(tokens.colors.text_secondary),
TextInput(
label: Some(cx.tr("contact.name.label").into()),
placeholder: Some(cx.tr("contact.name.placeholder").into()),
name: Some("name".into()),
required: true,
autofill_hints: vec!["name".into()],
error_text: name_error.clone().map(Into::into),
validation_message: name_error.clone(),
bind: form.name,
key: "contact-name",
semantics_identifier: "harbour.contact.name".to_owned(),
),
TextInput(
label: Some(cx.tr("contact.email.label").into()),
placeholder: Some(cx.tr("contact.email.placeholder").into()),
name: Some("email".into()),
required: true,
keyboard_type: TextInputType::EmailAddress,
autocorrect: false,
spell_check: false,
autofill_hints: vec!["email".into()],
error_text: email_error.clone().map(Into::into),
validation_message: email_error.clone(),
bind: form.email,
key: "contact-email",
semantics_identifier: "harbour.contact.email".to_owned(),
),
TextInput(
label: Some(cx.tr("contact.subject.label").into()),
placeholder: Some(cx.tr("contact.subject.placeholder").into()),
name: Some("subject".into()),
required: true,
max_length: Some(120),
error_text: subject_error.clone().map(Into::into),
validation_message: subject_error.clone(),
bind: form.subject,
key: "contact-subject",
semantics_identifier: "harbour.contact.subject".to_owned(),
),
TextInput(
label: Some(cx.tr("contact.message.label").into()),
placeholder: Some(cx.tr("contact.message.placeholder").into()),
name: Some("message".into()),
required: true,
multiline: true,
min_lines: Some(4),
max_lines: Some(7),
max_length: Some(2000),
error_text: message_error.clone().map(Into::into),
validation_message: message_error.clone(),
bind: form.message,
key: "contact-message",
semantics_identifier: "harbour.contact.message".to_owned(),
),
Button(
child: Text(cx.tr("contact.action.send")),
key: "check-contact-message",
on_press: reduce { form.checked = true; },
).semantics_identifier("harbour.contact.check-message".to_owned()),
if form.checked {
SemanticsRegion(
identifier: Some("harbour.contact.feedback".to_owned()),
label: Some(cx.tr(if error.is_some() {
"contact.error.generic"
} else {
"contact.success.preview"
})),
child: Text(cx.tr(if error.is_some() {
"contact.error.generic"
} else {
"contact.success.preview"
})),
)
} else {
Text(cx.tr("contact.next"))
},
Button(
child: Text(cx.tr("contact.action.new")),
key: "clear-contact-message",
variant: ButtonVariant::Outline,
on_press: reduce {
form.name.clear();
form.email.clear();
form.subject.clear();
form.message.clear();
form.checked = false;
},
).semantics_identifier("harbour.contact.clear-message".to_owned()),
]))
.width_length(Length::percent(100.0))
.max_width(720.0)
.padding_all(tokens.spacing.l)
.bg(tokens.colors.surface),
),
).height_length(Length::vh(100.0))
}
{"id":"fission-tabs-1","index":2,"label":"src/lib.rs","value":"src-lib-rs"}
mod validation;
mod app;
mod translations;
use fission::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<(), _>::new(app::ContactForm::new())
.with_env(translations::create_env())
.run()
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
console_error_panic_hook::set_once();
WebApp::<(), _>::new(app::ContactForm::new())
.with_env(translations::create_env())
.with_title("Harbour Supply contact request")
.mount("#fission-web-mount")
.run()
.map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":3,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod validation;
mod app;
mod translations;
use fission::prelude::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
WebApp::<(), _>::new(app::ContactForm::new())
.with_env(translations::create_env())
.with_title("Harbour Supply contact request")
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
Check an incomplete draft. The error belongs beside the first invalid field, while the other answers remain. Complete the form, check it again, then empty the message: the ready feedback must disappear.
Show the app previewHide the app preview
Show the app preview
Hide the app preview