2011-01-13 51 views
1

我已經被引導到一篇非常好的文章,展示瞭如何從頭到尾創建自定義驗證器。我唯一的問題是,這隻適用於單個字段: http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspxASP.NET MVC 2:自定義驗證,訪問整個模型?

如果我需要在我的模型中驗證2個或更多屬性,該怎麼辦?我怎樣才能將我的整個模型傳遞給Validator?

注意:爲了清楚起見,我真的不希望在回發時不得不求助於驗證整個模型......這會挫敗此方法的目的。

回答

5

你需要使用一個自定義的驗證屬性,並用它裝點你的模型,而不是單個屬性:

[AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 
public class MyCustomValidatorAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     // value here will be the model instance you could cast 
     // and validate properties 
     return true; 
    } 
} 

,然後用它裝點你的模型:

[MyCustomValidator] 
public class MyViewModel 
{ 
    public string Prop1 { get; set; } 
    public string Prop2 { get; set; } 
} 

作爲替代數據執行驗證的註釋我會比強烈推薦您FluentValidation.NET。它也有great integration with ASP.NET MVC

+0

``[AttributeUsage(AttributeTargets.Class)]`? – hunter 2011-01-13 18:39:07