FluentValidation

FluentValidation — FluentValidation documentation

 

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
  }
}

  

 

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; }
    }
}

  

 

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;
        }
    }
}

  

 

//模型验证注入
builder.Services.AddScoped<IValidator<AddUserCommand>, AddUserCommandValidator>();

  

posted on 2024-04-22 20:31  是水饺不是水饺  阅读(9)  评论(0编辑  收藏  举报

导航