更新 : 2019-04-21
原生的 rule https://fluentvalidation.net/built-in-validators
更新 : 2018-02-14
补上一个 manual 调用的方法.
refre : https://stackoverflow.com/questions/17138749/how-to-manually-validate-a-model-with-attributes
var context = new ValidationContext(student, serviceProvider: null, items: null); var validationResults = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(student, context, validationResults, true);
refer :
https://www.exceptionnotfound.net/custom-validation-in-asp-net-web-api-with-fluentvalidation/
https://github.com/JeremySkinner/FluentValidation
这是一个开源的小工具,用来出来 model validation
MVC,Web Api 都可以使用, Entity Framework 我就不太清楚
我只用到 Web Api 的 ^^
这个工具是可以和原本的 data annotations validation 一起使用的
我是因为 ComplexType 需要不同的验证和需要 conditional 验证才选择这个工具的.
nuget :
Install-Package FluentValidation.WebAPI
public static partial class Config { public static void Register(HttpConfiguration config) { FluentValidationModelValidatorProvider.Configure(config); } }
基本用法 :
[Validator(typeof(TestModelValidator))] public class Test { public Test() { this.address = new Address(); } [Key] public int Id { get; set; } public string email { get; set; } public bool needValidAddress { get; set; } public Address address { get; set; } } public class TestModelValidator : AbstractValidator<Test> { public TestModelValidator() { RuleFor(x => x.address.text) .NotEmpty() .SetValidator(new CustomValidator<int>()) .When(o => o.needValidAddress) .WithMessage("address text required"); When(o => !string.IsNullOrWhiteSpace(o.email), () => { RuleFor(c => c.email).Matches(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); }); Custom(o => { return o.Id >= 10 ? new ValidationFailure("Id","more than 10") : null; }); } } public class CustomValidator<T> : PropertyValidator { public CustomValidator() : base("Property {PropertyName} contains more than 10 items!") { } protected override bool IsValid(PropertyValidatorContext context) { var list = context.PropertyValue as IList<T>; if (list != null && list.Count >= 10) { return false; } return true; } } [ComplexType] public class Address { public string text { get; set; } }
.NotEmpty() 和 [Required] 一样, 使用的是 string.IsNullOrWhiteSpace