Avalonia Field Guide
About

Module 2 · Lesson 07 of 16

Validation that blocks the button

Errors belong to the view model. INotifyDataErrorInfo plus CanExecute is the whole validation story.

30 minHeadless-tested

There are two ways to validate a form in Avalonia: decorate a model with DataAnnotations and opt the validator in, or implement INotifyDataErrorInfo. The second is more code and far less magic. This lesson uses it because you can see exactly when errors appear and why the button is disabled.

src/CourseApp/Lessons/07_Forms/SignupViewModel.cs
using System.ComponentModel;
using System.Collections;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace CourseApp.Lessons.Forms;

public partial class SignupViewModel : ObservableObject, INotifyDataErrorInfo
{
    readonly Dictionary<string, string> _errors = [];

    [ObservableProperty]
    private string _email = "";

    [ObservableProperty]
    private string _password = "";

    [ObservableProperty]
    private string _status = "";

    [ObservableProperty]
    private string _emailError = "";

    [ObservableProperty]
    private string _passwordError = "";

    [ObservableProperty]
    private bool _hasEmailError;

    [ObservableProperty]
    private bool _hasPasswordError;

    public bool HasErrors => _errors.Count > 0;

    public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;

    public IEnumerable GetErrors(string? propertyName) =>
        propertyName is not null && _errors.TryGetValue(propertyName, out var error)
            ? new[] { error }
            : Array.Empty<string>();

    partial void OnEmailChanged(string value) => ValidateEmail();

    partial void OnPasswordChanged(string value) => ValidatePassword();

    void ValidateEmail()
    {
        SetError(nameof(Email), Email.Contains('@') && Email.Contains('.') ? null : "Enter a valid email address.");
        EmailError = _errors.GetValueOrDefault(nameof(Email), "");
        HasEmailError = EmailError.Length > 0;
        RefreshSubmit();
    }

    void ValidatePassword()
    {
        SetError(nameof(Password), Password.Length >= 8 ? null : "Use at least 8 characters.");
        PasswordError = _errors.GetValueOrDefault(nameof(Password), "");
        HasPasswordError = PasswordError.Length > 0;
        RefreshSubmit();
    }

    void SetError(string property, string? error)
    {
        var had = _errors.ContainsKey(property);
        if (error is null)
            _errors.Remove(property);
        else
            _errors[property] = error;

        if (had != _errors.ContainsKey(property) || error is not null)
            ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(property));
    }

    [RelayCommand(CanExecute = nameof(CanSubmit))]
    private void Submit()
    {
        Status = $"Account created for {Email}.";
    }

    bool CanSubmit() =>
        Email.Length > 0 && Password.Length > 0 && !HasEmailError && !HasPasswordError;

    void RefreshSubmit() => SubmitCommand.NotifyCanExecuteChanged();
}
Screenshot of the forms lesson sample
The lesson's sample, rendered headlessly at 1280×800. Light and dark are both captured.

The contract

INotifyDataErrorInfo has three parts:

  • HasErrors — the summary a submit command can consult.
  • GetErrors(propertyName) — the errors for one field.
  • ErrorsChanged — the notification that tells the binding to re-query.

The sample stores one message per field:

readonly Dictionary<string, string> _errors = [];

Validation runs from the generated property-changed hooks, so every keystroke re-evaluates the field and then refreshes the submit command. Nothing waits for a LostFocus event.

Avalonia 12 does not enable DataAnnotations validation by default. If you come from WPF, [Required] alone will do nothing until you register the validator plugin. Starting with INotifyDataErrorInfo avoids that surprise entirely and gives you the same result.

Showing the error

The view binds visibility to a bool rather than a converter, because the property exists anyway:

<TextBlock Text="{Binding EmailError}" IsVisible="{Binding HasEmailError}" />

DataValidationErrors can also draw a red border for you if you enable it, but a message under the field is more useful than a colour, and it survives colour-blindness and dark mode without tuning.

Blocking submission

[RelayCommand(CanExecute = nameof(CanSubmit))]
void Submit() { … }

bool CanSubmit() =>
    Email.Length > 0 && Password.Length > 0 && !HasEmailError && !HasPasswordError;

RefreshSubmit() calls NotifyCanExecuteChanged() after each validation pass. The button is disabled by the command, not by a clever style — which means the same rule protects a keyboard shortcut or an API call.

Try it

  1. Add a confirm-password field and a cross-field rule (the two must match). Note that changing either field has to revalidate both.
  2. Replace the email check with MailAddress.TryCreate and keep the same shape.
  3. Move the rules into a Validate() method returning a list of messages, so the view model and a future server-side validator can share them.

Next: two screens, one ContentControl.

Files this lesson draws from

  • src/CourseApp/Lessons/07_Forms/SignupViewModel.cs
  • src/CourseApp/Lessons/07_Forms/SignupView.axaml

VerifiedThe verifier feeds an invalid email and a short password, asserts the errors are reported and submit is blocked, then supplies valid values and asserts the command becomes available.

Back to top