基于.NET的FluentValidation数据验证实现
public class Store { public People Peoples { get; set; } } public class Customer : People { public string Address { get; set; } } public class People { public string Name { get; set; } } 验证器如下: public class StoreValidator : AbstractValidator<Store> { public StoreValidator() { RuleFor(t => t.Peoples).NotNull().SetInheritanceValidator(t => { t.Add<Customer>(new CustomerValidator()); }); } } public class CustomerValidator : AbstractValidator<Customer> { public CustomerValidator() { RuleFor(t => t.Address).NotEmpty(); } } 覆盖消息 通过在验证程序上调用 WithMessage 方法, 可以覆盖验证程序的默认验证错误消息。错误提示中,可以通过 {PropertyName} 占位符替换属性名。除了 {PropertyName} 占位符,框架还内置了:{PropertyValue}、{ComparisonValue}、{MinLength}、{MaxLength}和{TotalLength} 占位符,关于更多内置占位符,可以参阅官方文档。 RuleFor(customer => customer.Surname).NotNull().WithMessage("Please ensure you have entered your {PropertyName}"); 验证程序支持通过 WithName 方法来指定属性别名,以下代码输出姓名不能为空。请注意,这仅替换错误消息中属性的名称。当您检查上的Errors集合时ValidationResult,此错误仍将与一个名为的属性相关联Surname。如果要完全重命名该属性,则可以使用OverridePropertyName方法。 RuleFor(customer => customer.Surname).NotNull().WithName("姓名"); 条件 When 和 Unless方法可用于执行满足指定条件情况下的规则,例如只当Surname属性不为空的时候,才执行前面的Name属性的非空验证(Unless和When是相反的所以这边只讲When就行啦!): RuleFor(t => t.Name).NotEmpty().When(t => !string.IsNullOrEmpty(t.Surname)); 如果需要指定多个规则在相同的条件下才执行验证,可以直接用顶级的When方法: (编辑:西安站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |