You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使.NET MAUI的UI输入验证正常工作?

.NET MAUI UI输入验证可行方案

一、自定义Behavior实现控件级验证

这是MAUI原生支持的方式,完全不依赖第三方包,灵活可控。比如做一个邮箱输入验证:

代码实现

using System.Text.RegularExpressions;
using Microsoft.Maui.Controls;

public class EmailValidationBehavior : Behavior<Entry>
{
    private const string EmailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";

    protected override void OnAttachedTo(Entry entry)
    {
        entry.TextChanged += CheckValidation;
        base.OnAttachedTo(entry);
    }

    protected override void OnDetachingFrom(Entry entry)
    {
        entry.TextChanged -= CheckValidation;
        base.OnDetachingFrom(entry);
    }

    private void CheckValidation(object sender, TextChangedEventArgs e)
    {
        var entry = sender as Entry;
        bool isValid = !string.IsNullOrWhiteSpace(e.NewTextValue) && 
                       Regex.IsMatch(e.NewTextValue, EmailPattern);
        
        // 用文字颜色提示验证状态
        entry.TextColor = isValid ? Colors.Black : Colors.Red;
        
        // 也可以绑定到ViewModel的验证状态属性
        if (BindingContext is ILoginViewModel vm)
        {
            vm.IsEmailValid = isValid;
        }
    }
}

XAML使用

<Entry Placeholder="请输入邮箱">
    <Entry.Behaviors>
        <local:EmailValidationBehavior />
    </Entry.Behaviors>
</Entry>

二、ViewModel层面的DataAnnotations验证

利用.NET自带的DataAnnotations特性,结合INotifyDataErrorInfo实现全局验证,适合复杂表单场景。

ViewModel实现

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;

public class LoginViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
    private readonly Dictionary<string, List<string>> _errorDict = new();
    private string _email;

    public string Email
    {
        get => _email;
        set
        {
            _email = value;
            ValidateEmail();
            OnPropertyChanged();
        }
    }

    private void ValidateEmail()
    {
        var errors = new List<string>();
        if (string.IsNullOrWhiteSpace(Email))
        {
            errors.Add("邮箱不能为空");
        }
        else if (!Regex.IsMatch(Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
        {
            errors.Add("请输入有效的邮箱格式");
        }

        if (errors.Any())
        {
            _errorDict["Email"] = errors;
        }
        else
        {
            _errorDict.Remove("Email");
        }

        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs("Email"));
    }

    // INotifyDataErrorInfo 接口实现
    public bool HasErrors => _errorDict.Any();
    public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
    public IEnumerable GetErrors(string? propertyName)
    {
        if (string.IsNullOrEmpty(propertyName) || !_errorDict.ContainsKey(propertyName))
            return Enumerable.Empty<string>();
        return _errorDict[propertyName];
    }

    // INotifyPropertyChanged 接口实现
    public event PropertyChangedEventHandler? PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string? propName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }
}

XAML绑定与错误提示

<Entry Text="{Binding Email, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}" 
       Placeholder="请输入邮箱"/>
<Label Text="{Binding [Email], Mode=OneWay}" 
       TextColor="Red" 
       IsVisible="{Binding HasErrors}"/>

三、社区工具包验证功能的修复建议

如果坚持用CommunityToolkit.Maui的验证,试试这些排查步骤:

  • 确保NuGet包是最新稳定版:更新CommunityToolkit.Maui和CommunityToolkit.Mvvm到当前最新版
  • 检查项目初始化:在MauiProgram.cs中必须添加builder.UseMauiCommunityToolkit();
  • 验证ViewModel是否正确继承ObservableValidator:
    public class RegisterViewModel : ObservableValidator
    {
        [Required(ErrorMessage = "用户名不能为空")]
        [MinLength(3, ErrorMessage = "用户名至少3个字符")]
        public string Username { get; set; } = string.Empty;
    }
    
  • 绑定开启验证:XAML中绑定要加上ValidatesOnNotifyDataErrors=True
  • 清理重建项目:删除bin、obj文件夹,重启VS后重新编译

内容的提问来源于stack exchange,提问作者BuckBuchanan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:16:01