Model a form as editable state, then connect controls to it: signals in a declarative view, or a view model with bindings in XAML. Keep validation messages next to their inputs and provide a clear result for submission. The validation rule itself is ordinary Rust either way.
Write the form in declarative Rust
Section titled “Write the form in declarative Rust”use ferroui_view::prelude::*;
#[component]pub fn ProfileForm() -> Element { let display_name = signal(String::new()); let error = memo(move |_| match validate_display_name(&display_name.get()) { Ok(()) => String::new(), Err(message) => message.to_string(), }); rsx! { StackPanel { spacing: 8.0, TextBlock { text: "Display name" } TextBox { text: display_name.two_way(), placeholder_text: "Enter a name" } TextBlock { text: error } Button { is_enabled: move || error.with(|error| error.is_empty()), on_click: move |_| save_profile(&display_name.get_untracked()), "Save" } } }}validate_display_name is the rule shown below and save_profile stands for the application’s save call. The memo recomputes the message on every edit of the field; the message and the button’s availability follow it. A memo only notifies when its value changes, so an unchanged message does no work.
Write the form in XAML
Section titled “Write the form in XAML”This fragment uses explicit reflection bindings because it omits your application’s registered source types. See compiled binding setup for typed XAML.
<StackPanel xmlns="https://github.com/ferroui" Spacing="8"> <TextBlock Text="Display name" /> <TextBox Text="{ReflectionBinding DisplayName, Mode=TwoWay}" PlaceholderText="Enter a name" /> <TextBlock Text="{ReflectionBinding NameError}" /> <Button Content="Save" Command="{ReflectionBinding SaveCommand}" /></StackPanel>Define what the view model exposes
Section titled “Define what the view model exposes”The markup above is a view fragment. It needs a registered data context with this contract:
| Property | Responsibility |
|---|---|
DisplayName |
Editable text; notify when it changes |
NameError |
A readable error, or an empty string when valid |
SaveCommand |
Validate, persist, and report the result |
Keep the rule usable independently of controls, whichever way the view is written. For example:
fn validate_display_name(value: &str) -> Result<(), &'static str> { if value.trim().is_empty() { Err("Enter a display name.") } else if value.chars().count() > 80 { Err("Use 80 characters or fewer.") } else { Ok(()) }}
assert_eq!(validate_display_name(" "), Err("Enter a display name."));assert!(validate_display_name("Ada").is_ok());Call the rule when the field changes if you want immediate feedback, and again before saving. In a view model, update NameError through a notifying setter; in a declarative view, a memo of the field does this. Domain-specific length rules may need grapheme counting rather than the Unicode scalar count used in this small example.
The MVVM guide explains property registration; the commands guide connects SaveCommand to the control.
Separate editing from persistence
Section titled “Separate editing from persistence”A two-way binding or a two-way signal changes form state. It should not save to disk or a remote service on every keystroke unless that is an intentional autosave workflow. A save command can validate the complete form, persist it, and expose success or failure state.
Use domain validation for rules such as uniqueness or allowed ranges. Use control constraints, such as numeric bounds, to make invalid input less likely. Neither replaces the other when data can enter through another path.
Represent errors accessibly
Section titled “Represent errors accessibly”Do not rely only on a red border. Add an understandable message, associate the label with its input, and ensure keyboard users can reach the first invalid field. Keep user-entered values when submission fails.
Avoid update loops
Section titled “Avoid update loops”A setter may normalize a value, but it should raise a notification only when the effective value changes. Repeatedly setting an unchanged value can produce unnecessary binding work and make caret behavior surprising.
Test the validation rule and the view model’s command availability without opening a window. Then test focus, keyboard submission, and the rendered validation state in the real application.
Verify the form
Section titled “Verify the form”Try an empty name, whitespace, a valid name, and a failed save. The message should explain the correction, a failed save should keep the text, and a second click should not start an unintended duplicate operation. Repeat with keyboard input and a long localized error message.
Try the controls
Section titled “Try the controls”Try text entry here. Validation and saving need the view-model contract described above and are not supplied by this preview.
Real controls, running in WebAssembly.
The runtime downloads when you press Run.
<StackPanel xmlns="https://github.com/ferroui" Spacing="12"> <TextBlock Text="Your name" /> <TextBox PlaceholderText="Enter a display name" /> <TextBox Text="Try editing this text" /></StackPanel>use ferroui::prelude::*;use ferroui::base::metadata::from_markup_value;use ferroui::markup_xaml_loader::FerroRuntimeXamlLoader;
#[repr(C)]pub struct App { base: Application,}
ferro_class!(App: Application);ferro_impl_classes!(App: FerroObjectImpl);
impl NewApplication for App { fn new_application() -> Ref<Self> { instantiate(Self { base: Application::construct() }) }}
impl ApplicationImpl for App { fn initialize(this: &Self) { Self::parent_initialize(this); ferroui::controls::register_types(); FerroRuntimeXamlLoader::register(); this.styles().add(FluentTheme::new().as_style()); }
fn on_framework_initialization_completed(this: &Self) { let lifetime = this.application_lifetime(); if let Some(desktop) = lifetime.as_ref().and_then(|l| l.as_classic_desktop_style_application_lifetime()) { let value = FerroRuntimeXamlLoader::load(include_str!("View.xaml"), None, None, None, false) .expect("Example XAML should load"); let view = from_markup_value::<Ref<Control>>(&Some(value)).expect("Example root must be a control"); let window = Window::new(); window.set_title(Some("FerroUI documentation example".to_owned())); window.set_width(560.0); window.set_height(420.0); window.set_padding(Thickness::uniform(24.0)); window.set_content(Some(Control::boxed(view))); desktop.set_main_window(Some(window)); } Self::parent_on_framework_initialization_completed(this); }}
fn main() -> std::process::ExitCode { let args: Vec<String> = std::env::args().skip(1).collect(); let result = AppBuilder::configure::<App>().use_platform_detect().start_with_classic_desktop_lifetime(&args); std::process::ExitCode::from(result as u8)}Public APIs and controls
Section titled “Public APIs and controls”memoandsignal— declarative form state and derived messages.- TextBox — editing and text properties.
- TextBlock — visible validation messages.
- Button and
ReactiveCommand— submission and availability. AutomationProperties— accessible labels and relationships.