Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 42 ยท Controls and Binding

Input Validation and Forms

Validate user input in .NET MAUI forms: Entry behaviors, the Community Toolkit validation behaviors, INotifyDataErrorInfo, validation rules in the view model and a runnable validator stand-in.

Users mistype emails, leave required fields empty and invent phone numbers. A good form tells them what is wrong, early and politely, and never lets bad data reach your database or server. In this lesson you build the validation layer of a .NET MAUI form: rules, error messages, when to show them and how to keep the logic testable.

MAUI controls and the Community Toolkit cannot run on this site, so their XAML is read-only. The validation rules are plain C#, so they run here as labelled stand-ins, and they are the same code you would put in a real view model.

Where validation belongs

There are three layers, and you usually want all of them:

  1. Input hints: Keyboard="Email", MaxLength, pickers instead of free text. They prevent many mistakes.
  2. View-level feedback: red text, an icon, a disabled Save button, as the user types.
  3. Rules in code: the real truth, run again before saving, and on the server too, because a client can always be bypassed.

Keeping rules in the view model (or a separate validator class) lets you unit test them, as you will do in Unit Testing View Models.

A simple rule class

Start with the rules themselves:

C#
public static class Rules
{
    public static string? Required(string? value, string fieldName) =>
        string.IsNullOrWhiteSpace(value) ? $"{fieldName} is required." : null;

    public static string? Email(string? value)
    {
        if (string.IsNullOrWhiteSpace(value)) return null;     // Required handles empty
        return System.Net.Mail.MailAddress.TryCreate(value, out var m) && m.Address == value
            ? null
            : "Enter a valid email address.";
    }

    public static string? MinLength(string? value, int length, string fieldName) =>
        value is { Length: var l } && l >= length ? null : $"{fieldName} needs at least {length} characters.";
}

A rule returns null when the value is fine and a message when it is not. Small functions like these compose: a field has a list of rules, and the first message wins.

C# Stand-in: rule-based validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Behaviors on the control

A behavior attaches extra logic to a control from XAML. MAUI includes none for validation, but the free .NET MAUI Community Toolkit (a separate NuGet package) provides several, such as EmailValidationBehavior, TextValidationBehavior, NumericValidationBehavior, RequiredStringValidationBehavior and UriValidationBehavior:

XML
<Entry Placeholder="Email" Keyboard="Email" x:Name="emailEntry">
    <Entry.Behaviors>
        <toolkit:EmailValidationBehavior
            x:Name="emailValidator"
            Flags="ValidateOnValueChanged"
            InvalidStyle="{StaticResource InvalidEntry}"
            ValidStyle="{StaticResource ValidEntry}" />
    </Entry.Behaviors>
</Entry>
<Label Text="Enter a valid email address."
       TextColor="Red"
       IsVisible="{Binding IsNotValid, Source={x:Reference emailValidator}}" />

Flags such as ValidateOnValueChanged, ValidateOnUnfocusing and ForceMakeValidWhenFocused control when checking happens. IsValid, IsNotValid and IsRunning are bindable properties of the behavior. The package must be registered with .UseMauiCommunityToolkit() in MauiProgram (see App Lifecycle and MauiProgram).

A custom behavior is a class that derives from Behavior<Entry> and hooks events in OnAttachedTo and unhooks them in OnDetachingFrom. It is good for UI reactions; keep business rules out of it.

Validation in the view model with INotifyDataErrorInfo

INotifyDataErrorInfo is a .NET interface made for forms: the object exposes HasErrors, GetErrors(propertyName) and an ErrorsChanged event. The CommunityToolkit.Mvvm package builds on it with ObservableValidator and System.ComponentModel.DataAnnotations attributes:

C#
public partial class SignUpViewModel : ObservableValidator
{
    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Required(ErrorMessage = "Email is required.")]
    [EmailAddress(ErrorMessage = "Enter a valid email address.")]
    private string email = "";

    [ObservableProperty]
    [NotifyDataErrorInfo]
    [MinLength(8, ErrorMessage = "At least 8 characters.")]
    private string password = "";

    [RelayCommand]
    private async Task SaveAsync()
    {
        ValidateAllProperties();
        if (HasErrors) return;
        await service.CreateAccountAsync(Email, Password);
    }
}

Showing the first error text for a field can be done with a binding to GetErrors("Email") through a small converter or helper property. Because MAUI does not display INotifyDataErrorInfo errors by itself (unlike WPF), you still write the red label; the interface just gives you a consistent source.

The stand-in below uses the real DataAnnotations attributes and Validator class from .NET (both are standard and run on Piston) to validate an object the way ObservableValidator does.

C# Stand-in: DataAnnotations validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When to show errors

Showing "Email is required" while the user is still typing the first letter feels rude. Common approaches:

  • Validate on unfocus (when the user leaves the field) for the first time, then on every change to give quick positive feedback after an error was shown.
  • Validate everything on Save, scroll to the first error and focus that field with entry.Focus().
  • Keep the Save button enabled and show the problems, rather than silently disabling it: a disabled button does not tell users what to fix.

Use accessible feedback too: do not rely on colour alone (add text or an icon), and set SemanticProperties.Description so screen readers announce the message.

Server-side validation

Client checks improve the experience, but only the server can enforce rules. Treat the server's answer as another source of errors: map a 400 response with field messages to the same error list your form already shows, as the REST lesson does with problem details.

Layers of form validation

Input hints Keyboard, MaxLength, pickers
Live feedback Behaviors and error labels
Rules in code Testable view-model logic
Server checks The only rules you can trust

Use all four; never rely on the UI alone.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must validation also run on the server?

    Client-side checks are for user experience. Anyone can send requests directly, so the server must validate again.
  2. 2. What does a rule method return in the pattern used in this lesson?

    Returning null for "no problem" and a message otherwise lets you compose rules and show the first error.
  3. 3. Which interface lets an object report per-property errors to a form?

    INotifyDataErrorInfo exposes HasErrors, GetErrors and ErrorsChanged for property-level validation.
  4. 4. Which timing for showing an error is friendliest the first time?

    Waiting until the user finishes the field avoids showing errors for input that is simply incomplete.

Summary

  • Combine input hints, live feedback, testable rules and server validation.
  • Keep rules in plain C# (null for valid, message for invalid) so they run in unit tests.
  • Community Toolkit behaviors and ObservableValidator with DataAnnotations are the usual tools; you still draw the error text yourself.
  • Show errors after the user leaves a field or presses Save, and do not rely on colour alone.

Next: The MVVM Pattern