从现在开始,我使用了优秀的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) 我刚开始使用ASP.NET MVC 2,并且正在使用Validation.
假设我有2个属性:
我想要求它们都被填写,并要求在模型有效之前两者都相同.
我有一个名为"NewUser"的简单类.
我该如何实现?我已经阅读了ValidationAttribute,并了解这一点.但我不知道如何使用它来实现比较两个或更多属性与eathother的验证.
提前致谢!
以下解决方案的问题:
当这应用到应用程序,并且运行ModelBinder的模型的验证,则存在是一个问题:
如果房产级ValidationAttribute包含一个错误,那么类级别ValidationAttribute的是不是验证.我还没有找到解决这个问题的方法.
如果您有解决此问题的方法,请分享您的经验.非常感谢!