开箱即用的ASP.NET MVC不提供内剃刀验证模型的能力。不幸的是,这是使用属性进行模型验证的问题之一。
从这里,你必须提供给您两种选择:
- 创建一个中介类,然后映射回组件中的模型。
- 使用像FluentValidation这样的验证库,允许您创建验证规则,而无需通过灵活且可扩展的流畅API访问模型。例如:
。
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
}
}
然后你验证你的模型像这样:
var validator = new YourModelValidator();
ValidationResult results = validator.Validate(yourModel);
就个人而言,我会选择第二种方法。 Fluent Validation是一个梦幻般的库,它不需要很长的时间就可以实现,并且比ASP.NET的当前实现更好地验证模型(在我看来 - 尽管这对ASP.NET人来说毫无意义,但这正是使OSS很棒)。
然后使用视图模型,将验证属性应用于其属性并将数据模型映射到它。为了使用数据模型获得客户端验证,您需要手动添加所有适当的'data-val- *'属性,然后在提交表单时再次手动检查控制器中的所有内容。 –
这不会直接回答你的问题,但它提供了一个替代方案。有一个名为Fluent Validation的项目,它允许您为模型外的模型创建验证规则。 https://github.com/JeremySkinner/FluentValidation – AndyJ
AndyJ,谢谢你我会尝试 – Kate