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>();

  

posted on   是水饺不是水饺  阅读(17)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

导航

< 2025年3月 >
23 24 25 26 27 28 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 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示