FluentValidation
FluentValidation — FluentValidation documentation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class CustomerValidator : AbstractValidator<Customer> { public CustomerValidator() { RuleFor(x => x.Surname).NotEmpty(); RuleFor(x => x.Forename).NotEmpty().WithMessage( "Please specify a first name" ); RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount); RuleFor(x => x.Address).Length(20, 250); RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage( "Please specify a valid postcode" ); } private bool BeAValidPostcode( string postcode) { // custom postcode validating logic goes here } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using MediatR; using System.Runtime.Serialization; namespace WebApplication1.Handles { /// <summary> /// 添加User实体 命令 /// </summary> public class AddUserCommand : IRequest< bool > { public AddUserCommand( string userName, int age , string email) { UserName = userName; Age = age; Email = email; } public string Email { get ; set ; } public string UserName { get ; set ; } public int Age { get ; set ; } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using FluentValidation; using WebApplication1.Handles; namespace WebApplication1.Validations { public class AddUserCommandValidator : AbstractValidator<AddUserCommand> { public AddUserCommandValidator() { RuleFor(user => user.Age).NotEmpty().WithMessage( "年龄不能为空" ).Must(ValidationAge).WithMessage( "年龄必须大于0" ); RuleFor(user => user.Email).NotEmpty().WithMessage( "邮箱不能为空" ).EmailAddress(FluentValidation.Validators.EmailValidationMode.Net4xRegex); RuleFor(user => user.UserName).NotEmpty().WithMessage( "用户名不能为空" ); } /// <summary> /// 验证年龄 大于0 /// </summary> /// <param name="age"></param> /// <returns></returns> private bool ValidationAge( int age) { return age > 0 ? true : false ; } } } |
1 2 | //模型验证注入 builder.Services.AddScoped<IValidator<AddUserCommand>, AddUserCommandValidator>(); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构