我想知道是否可以繞過驗證使用數據批註的一個屬性。由於我在多個頁面中使用模型,因此我需要在某些方面進行檢查,而在其他方面不需要進行檢查,所以我希望將其忽略。ASP.NET MVC 2旁路數據批註驗證
Thaks!
我想知道是否可以繞過驗證使用數據批註的一個屬性。由於我在多個頁面中使用模型,因此我需要在某些方面進行檢查,而在其他方面不需要進行檢查,所以我希望將其忽略。ASP.NET MVC 2旁路數據批註驗證
Thaks!
你可以使用FluentValidation,它使用外部驗證器類。在這種情況下,你會爲每個場景實現一個不同的驗證器類。
http://fluentvalidation.codeplex.com/
例子:
using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty()
.WithMessage("Please specify a first name");
}
}
public class CustomerValidator2: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
CustomerValidator2 validator2 = new CustomerValidator2();
ValidationResult results2 = validator2.Validate(customer);
results would have 2 validation errors
results2 would have 1 validation error for the same customer
我不認爲這是可能的數據註釋。我知道Microsoft企業庫驗證應用程序塊具有規則集的概念以對驗證進行分組。這允許您在多個規則集上驗證對象,例如默認規則集,並在某些頁面上驗證擴展規則集。數據註釋沒有類似規則集的東西。
下面是使用VAB一個例子:
public class Subscriber
{
[NotNullValidator]
[StringLengthValidator(1,200)]
public string Name { get; set; }
[NotNullValidator(Ruleset="Persistence")]
[EmailAddressValidator]
public string EmailAddress { get; set; }
}
我問類似的東西來此而回 - 簡短的答案是否定的。 http://stackoverflow.com/questions/2503735/conditional-required-attribute-for-validation我最終不得不編寫我自己的驗證系統。你可能會寫自己的模型活頁夾來處理它,但我從來沒有接近它。 – jeriley 2010-08-04 13:52:36
...這就是爲什麼他們說你應該爲每個視圖創建一個單獨的視圖模型;) – Necros 2010-08-05 00:07:21