FluentValidation:C#后端输入验证框架的官方文档解读

时间:2021-12-26 07:47:59

参照 FluentValidation 的官方文档写的例子,便利日后检察和使用。

原文:https://github.com/JeremySkinner/FluentValidation/wiki

 Home NuGet Packages Install-Package FluentValidation

For ASP.NET MVC integration:

Install-Package FluentValidation.MVC5

For ASP.NET Core:

Install-Package FluentValidation.AspNetCore

Example

using FluentValidation; public class CustomerValidator: AbstractValidator<Customer> { public CustomerValidator() { RuleFor(customer => customer.Surname).NotEmpty(); RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name"); RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount); RuleFor(customer => customer.Address).Length(20, 250); RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode"); } private bool BeAValidPostcode(string postcode) { // custom postcode validating logic goes here } } Customer customer = new Customer(); CustomerValidator validator = new CustomerValidator(); ValidationResult results = validator.Validate(customer); bool validationSucceeded = results.IsValid; IList<ValidationFailure> failures = results.Errors;

a. Index

Documentation table of contents

b. Creating a Validator

界说东西,及东西验证类

public class Customer { public int Id { get; set; } public string Surname { get; set; } public string Forename { get; set; } public decimal Discount { get; set; } public Address Address { get; set; } public List<string> AddressLines { get; set; } = new List<string>(); public IList<Order> Orders { get; set; } } /// <summary> /// 为Customer类界说一组法则,担任自AbstractValidator<Customer> /// </summary> public class CustomerValidator : AbstractValidator<Customer> { public CustomerValidator() { //多个验证法则 RuleFor(customer => customer.Surname).NotNull().NotEqual("foo"); //对调集中的每一项进行验证 RuleForEach(x => x.AddressLines).NotNull(); //复合属性验证的从头操作 RuleFor(customer => customer.Address).SetValidator(new AddressValidator()); //复合的调集属性验证的从头操作 RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()); //用Where要领选择性验证某些项 RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator()).Where(x => x.Cost != null); //界说名为“Names”的法则调集 RuleSet("Names", () => { RuleFor(x => x.Surname).NotNull(); RuleFor(x => x.Forename).NotNull(); }); } }

public class Address { public string Line1 { get; set; } public string Line2 { get; set; } public string Town { get; set; } public string County { get; set; } public string Postcode { get; set; } } public class AddressValidator : AbstractValidator<Address> { public AddressValidator() { RuleFor(address => address.Postcode).NotNull(); //etc } }

public class Order { public string ProductName { get; set; } public decimal? Cost { get; set; } } public class OrderValidator : AbstractValidator<Order> { public OrderValidator() { RuleFor(x => x.ProductName).NotNull(); RuleFor(x => x.Cost).GreaterThan(0); } }

挪用