2011-01-13 9 views
1

私は最初から最後までカスタムバリデーターを作成する方法を示す非常に良い記事になっています。私の唯一の問題は、これが単一フィールドでのみ機能することです。 http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspxASP.NET MVC 2:カスタム検証、モデル全体に​​アクセスできますか?

モデルで2つ以上のプロパティに対して検証する必要がある場合はどうなりますか? Model全体を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

+0

、投稿時に編集権が必要です – hunter