RequiresValidationContext は、CompareAttribute やカスタム属性などのバリデーターに役立ちます。
ValidationAttribute は抽象クラスであり、意味する実装によって異なります。たとえば、別のプロパティに何らかの値がある場合にのみ、一部のフィールドが必要であることを確認する検証属性があります。
IsValid(object value) が呼び出されるかどうかは、Attribute の実装に依存します。例えば:
[Display(Name = "Your employer")]
[LoginTypeRequired(LoginType = LoginType.Employee, ErrorMessage = "Employee must fill in Employer.")]
public int? Employer { get; set; }
属性コード:
public class LoginTypeRequiredAttribute : RequiredAttribute
{
public override bool RequiresValidationContext
{
get {return true;}
}
public LoginType LoginType { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
RegisterModel model = (RegisterModel)validationContext.ObjectInstance;
if (LoginType != model.LoginType)
return null;
else
return base.IsValid(value, validationContext);
}
public override bool IsValid(object value)
{
return base.IsValid(value);
}
}
2 つのパラメーターを持つ最初のメソッドは、IsValid(object value, ValidationContext validationContext) を使用して、コンテキストでジョブを実行します。すべて問題がなければ、ベースが呼び出され、内部の .NET 4.5 スタックは次のようになります。
LinqDataModel.dll!LinqDataModel.Models.LoginTypeRequiredAttribute.IsValid(オブジェクト値) 92 行目 C# System.ComponentModel.DataAnnotations.dll!System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(オブジェクト値, System.ComponentModel.DataAnnotations.ValidationContext validationContext) + 0x74バイト
LinqDataModel.dll!LinqDataModel.Models.LoginTypeRequiredAttribute.IsValid(オブジェクト値、System.ComponentModel.DataAnnotations.ValidationContext validationContext) 行 87 + 0xe バイト C# System.ComponentModel.DataAnnotations.dll!System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(オブジェクト値、System.ComponentModel.DataAnnotations.ValidationContext validationContext) + 0x1e バイト
System.Web.Mvc.dll!System.Web.Mvc.DataAnnotationsModelValidator.Validate.MoveNext() + 0xa2 バイトSystem.Web.Mvc.dll!System.Web.Mvc.ModelValidator.CompositeModelValidator.Validate.MoveNext() + 0x138 バイトSystem.Web.Mvc.dll!System.Web.Mvc.DefaultModelBinder.OnModelUpdated(System.Web.Mvc.ControllerContext controllerContext、System.Web.Mvc.ModelBindingContext bindingContext) + 0x212 バイト
したがって、IsValid(オブジェクト値、ValidationContext validationContext) がオーバーライドされていない場合に IsValid(オブジェクト値) を呼び出していることがわかります。
ただし、 IsValid(object value, ValidationContext validationContext) をオーバーライドして、ベースを呼び出さない可能性もあります。