我即将实现一个类来表示验证错误。该类肯定会包含一个名为 Message 的字符串值,这是向用户显示的默认消息。我还需要一种方法来向程序员表示验证错误是什么。这个想法是应该有一种简单的方法来确定是否发生了特定的验证错误。
实现一个名为 Type 的字符串成员会很简单,但要确定 ValidationError 是否属于该类型,我需要记住描述该类型的字符串。
if (validationError.Type == "PersonWithoutSurname") DoSomething();
显然,我需要更强类型的东西。枚举会很好:
if (validationError.Type == ValidationErrorType.PersonWithoutSurname) DoSomething();
但考虑到可能存在数百种类型的验证错误,我最终可能会得到一个包含数百个值的丑陋枚举。
我还想到了使用子类:
if (validationError.GetType() == typeof(PersonWithoutSurnameValidationError)) DoSomething();
但后来我的类库中充斥着数百个类,这些类大部分都将被使用一次。
你们是做什么的?我可以花几个小时为这种事情苦恼。
请回答提出我所用建议的任何人。枚举建议是最好的选择。
最佳答案
我使用 FluentValidation ,您可以在其中为每个类设置规则,为每个属性设置默认或可自定义的消息。
因为它是一个流畅的框架,您可以组合规则,例如:
RuleFor(customer => customer.Address)
.NotNull().Length(20, 250).Contains("Redmond")
.WithMessage(@"Address is required, it must contain
the word Redmond and must be between 20 and 250 characters in length.");
Customer 类验证器的典型用法:
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.Company).NotNull();
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;
//Bind these error messages to control to give validation feedback to user;
关于c# - C# 中 ValidationError 类的合理模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3364432/