開箱即用的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