# 03 - 表单验证示例 演示如何使用 Sharp.Wpf 的表单验证功能,包括 DataAnnotations 验证、实时错误提示和自定义验证。 ## 🎯 学习目标 - 使用 `ValidatableViewModelBase` 实现表单验证 - 掌握 DataAnnotations 验证特性 - 实现实时验证反馈 - 自定义验证规则 - 显示验证错误消息 ## 📦 使用的模块 - **Sharp.Wpf** - ValidatableViewModelBase, 验证支持 ## 🚀 快速运行 ```bash cd examples/03-FormValidation dotnet run ``` ## 📝 核心代码讲解 ### 1. UserViewModel.cs - 带验证的 ViewModel ```csharp using System.ComponentModel.DataAnnotations; using Wpf.Validation; public class UserViewModel : ValidatableViewModelBase { private string _username = ""; private string _email = ""; private string _password = ""; private string _confirmPassword = ""; private int _age; [Required(ErrorMessage = "用户名不能为空")] [StringLength(20, MinimumLength = 3, ErrorMessage = "用户名长度必须在3-20个字符之间")] public string Username { get => _username; set => SetProperty(ref _username, value, validate: true); // 启用验证 } [Required(ErrorMessage = "邮箱不能为空")] [EmailAddress(ErrorMessage = "邮箱格式不正确")] public string Email { get => _email; set => SetProperty(ref _email, value, validate: true); } [Required(ErrorMessage = "密码不能为空")] [StringLength(50, MinimumLength = 6, ErrorMessage = "密码长度必须在6-50个字符之间")] [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$", ErrorMessage = "密码必须包含大小写字母和数字")] public string Password { get => _password; set { SetProperty(ref _password, value, validate: true); // 密码变化时,重新验证确认密码 ValidateProperty(ConfirmPassword, nameof(ConfirmPassword)); } } [Required(ErrorMessage = "请确认密码")] public string ConfirmPassword { get => _confirmPassword; set { SetProperty(ref _confirmPassword, value, validate: false); // 自定义验证:确认密码必须与密码一致 if (value != Password) { AddError(nameof(ConfirmPassword), "两次密码输入不一致"); } else { ClearErrors(nameof(ConfirmPassword)); } } } [Range(18, 120, ErrorMessage = "年龄必须在18-120之间")] public int Age { get => _age; set => SetProperty(ref _age, value, validate: true); } // 提交命令 public ICommand SubmitCommand { get; } public UserViewModel(IDialogService dialogService) { SubmitCommand = new RelayCommand(() => { // 验证所有属性 if (ValidateAll()) { dialogService.ShowMessage( $"注册成功!\n用户名: {Username}\n邮箱: {Email}\n年龄: {Age}", "成功"); } else { dialogService.ShowMessage("请修正表单错误后再提交", "验证失败"); } }); } } ``` ### 2. MainWindow.xaml - 验证错误显示 ```xml