# Build and validate a form

Version: 0.5.0
Framework commit: d503df2befa756e681fcdc6250e9552dc7388bea
Canonical URL: /docs/0.5.0/guides/forms/

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

```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

This fragment uses explicit reflection bindings because it omits your application’s registered source types. See [compiled binding setup](/docs/0.5.0/xaml/compilation/#migrate-to-compiled-bindings-by-default) for typed XAML.

```xml
<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

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:

```rust
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](/docs/0.5.0/guides/mvvm/) explains property registration; the [commands guide](/docs/0.5.0/guides/commands/) connects `SaveCommand` to the control.

## 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

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

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

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


Try text entry here. Validation and saving need the view-model contract described above and are not supplied by this preview.

### Text entry

```xml
<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>
```

```rust
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)
}

```

[Download the complete desktop project](/docs/0.5.0/generated/examples/text-box.zip). The browser preview runs real FerroUI controls with precompiled Rust support; this desktop application loads the same XAML.


## Public APIs and controls

- [`memo`](/docs/0.5.0/api/ferroui-view/reactive/function-memo/) and [`signal`](/docs/0.5.0/api/ferroui-view/reactive/function-signal/) — declarative form state and derived messages.
- [TextBox](/docs/0.5.0/controls/reference/textbox/) — editing and text properties.
- [TextBlock](/docs/0.5.0/controls/reference/textblock/) — visible validation messages.
- [Button](/docs/0.5.0/controls/reference/button/) and [`ReactiveCommand`](/docs/0.5.0/api/ferroui-reactiveui/reactive_command/struct-reactivecommand/) — submission and availability.
- [`AutomationProperties`](/docs/0.5.0/api/ferroui-controls/automation/struct-automationproperties/) — accessible labels and relationships.
