Aller au contenu

Validation

Signaler une saisie incorrecte sous le champ, et bloquer l'envoi tant qu'elle l'est.

ObservableValidator + DataAnnotations

using System.ComponentModel.DataAnnotations;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

public partial class InscriptionViewModel : ObservableValidator
{
    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Required(ErrorMessage = "Le nom est obligatoire.")]
    [MinLength(2, ErrorMessage = "2 caractères minimum.")]
    public partial string Nom { get; set; } = "";

    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Required(ErrorMessage = "L'e-mail est obligatoire.")]
    [EmailAddress(ErrorMessage = "E-mail invalide.")]
    public partial string Email { get; set; } = "";

    [ObservableProperty]
    [NotifyDataErrorInfo]
    [Range(18, 120, ErrorMessage = "Vous devez être majeur.")]
    public partial int Age { get; set; } = 18;

    [RelayCommand]
    private void Valider()
    {
        ValidateAllProperties();
        if (HasErrors) return;
        // envoyer…
    }
}
<StackPanel Spacing="12" MaxWidth="360">
  <TextBox Text="{Binding Nom}" PlaceholderText="Nom" />
  <TextBox Text="{Binding Email}" PlaceholderText="E-mail" />
  <NumericUpDown Value="{Binding Age}" Minimum="0" />
  <Button Content="S'inscrire" Command="{Binding ValiderCommand}" Classes="accent" />
</StackPanel>

Les messages apparaissent automatiquement sous chaque champ (thème Fluent).

Aperçu · validation en direct (simulée en HTML)
2 caractères minimum.
E-mail invalide.
sequenceDiagram
  participant T as TextBox
  participant VM as InscriptionViewModel
  T->>VM: Email = "pas-un-email"
  VM->>VM: [EmailAddress] échoue
  VM-->>T: ErrorsChanged("Email")
  T->>T: :error + message sous le champ

v12

Le plugin de validation DataAnnotations d'Avalonia est désactivé par défaut. Les attributs ne sont plus lus directement par Avalonia : c'est ObservableValidator (via INotifyDataErrorInfo) qui les évalue. Vous pouvez supprimer l'appel DisableAvaloniaDataAnnotationValidation() des projets v11.

Bloquer le bouton tant qu'il y a des erreurs

public InscriptionViewModel()
{
    ErrorsChanged += (_, _) => ValiderCommand.NotifyCanExecuteChanged();
}

[RelayCommand(CanExecute = nameof(PeutValider))]
private void Valider() { /* … */ }

private bool PeutValider() => !HasErrors;

Règle personnalisée

[ObservableProperty]
[NotifyDataErrorInfo]
[CustomValidation(typeof(InscriptionViewModel), nameof(VerifierMotDePasse))]
public partial string MotDePasse { get; set; } = "";

public static ValidationResult? VerifierMotDePasse(string mdp, ValidationContext _)
    => mdp.Length >= 8 && mdp.Any(char.IsDigit)
        ? ValidationResult.Success
        : new ValidationResult("8 caractères dont un chiffre.");

Comparer deux champs

[ObservableProperty]
[NotifyDataErrorInfo]
[Compare(nameof(MotDePasse), ErrorMessage = "Les mots de passe diffèrent.")]
public partial string Confirmation { get; set; } = "";

Erreur posée manuellement (ex. serveur)

Avec INotifyDataErrorInfo fait main :

public partial class ConnexionViewModel : ObservableObject, INotifyDataErrorInfo
{
    private readonly Dictionary<string, List<string>> _erreurs = new();

    public bool HasErrors => _erreurs.Count > 0;
    public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;

    public IEnumerable GetErrors(string? propriete)
        => propriete is not null && _erreurs.TryGetValue(propriete, out var e) ? e : Array.Empty<string>();

    private void PoserErreur(string propriete, string? message)
    {
        if (message is null) _erreurs.Remove(propriete);
        else _erreurs[propriete] = new() { message };
        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propriete));
    }

    [ObservableProperty]
    public partial string Identifiant { get; set; } = "";

    [RelayCommand]
    private async Task ConnecterAsync()
    {
        var ok = await _auth.ConnecterAsync(Identifiant);
        PoserErreur(nameof(Identifiant), ok ? null : "Identifiant inconnu.");
    }
}

Afficher les erreurs ailleurs

<TextBox x:Name="ChampEmail" Text="{Binding Email}" />

<ItemsControl ItemsSource="{Binding #ChampEmail.(DataValidationErrors.Errors)}"
              Foreground="Crimson" />

Styler l'état d'erreur

<Style Selector="TextBox:error">
  <Setter Property="BorderBrush" Value="Crimson" />
</Style>

Le message sous le champ est dessiné par le contrôle DataValidationErrors : pour changer son apparence, redéfinissez son ControlTheme (voir ControlTheme et templates).

Ne valider qu'après la première saisie

ObservableValidator valide à chaque modification ; les champs vides au démarrage ne sont pas en erreur tant que ValidateAllProperties() n'est pas appelé. C'est généralement le comportement souhaité.