从现在开始,我使用了优秀的FluentValidation 库来验证我的模型类.在Web应用程序中,我将它与jquery.validate插件结合使用,以执行客户端验证.一个缺点是许多验证逻辑在客户端重复,不再集中在一个地方.
出于这个原因,我正在寻找替代方案.有许多例子出有表示数据注解的使用来执行模型验证.看起来很有希望.我无法找到的一件事是如何验证依赖于另一个属性值的属性.
我们以下面的模型为例:
public class Event
{
[Required]
public DateTime? StartDate { get; set; }
[Required]
public DateTime? EndDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想确保EndDate大于StartDate.我可以编写一个扩展ValidationAttribute的自定义验证属性,以便执行自定义验证逻辑.不幸的是我找不到获取模型实例的方法:
public class CustomValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// value represents the property value on which this attribute is applied
// but how to obtain the object instance to which this property belongs?
return true;
}
} …Run Code Online (Sandbox Code Playgroud)