gpt4 book ai didi

.net - 实现自定义 ValidationAttribute 时应该覆盖哪个 IsValid 方法

转载 作者:行者123 更新时间:2023-12-04 20:34:13 26 4
gpt4 key购买 nike

当我实现从 ValidationAttribute 类继承的自定义属性时,我总是覆盖 bool IsValid(object value)忽略原型(prototype)为 ValidationResult IsValid(objet value, ValidationContext validationContext) 的另一个方法.

也许,即使我不使用验证上下文或结果(我使用 EntityFramework 和 ModelState.IsValid Controller 属性的验证),我也应该重写第二种方法。或者继续忽略重载的方法。如果是这样,我是否可以根据调用属性验证的上下文使对象有效或无效?如下代码所示的情况是否有问题?

class StrictlyPreviousAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var dateTime = value as DateTime?;
return dateTime == null || dateTime <= DateTime.Today;
}
}

class PreviousAttribute : StrictlyPreviousAttribute
{
public override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var dateTime = value as DateTime?;

if(dateTime == DateTime.Today)
{
return ValidationResult.Success;
}
else
{
return base.IsValid(object);
}
}
}

我不知道是否存在对对象的误解,或者我是否遗漏了一些观点。是否有一种方法我应该最好覆盖而不是其他方法。我是否应该同时覆盖两者。

最佳答案

Steve Greene 在上述评论中提供的链接启发了方法之间的差异并回答了问题。

返回 bool 的方法仍然存在以实现向后兼容性,但自 .NET 4.0 以来不再是抽象的。建议覆盖有权访问 ValidationContext 的方法.

This (amongst other things) gives us access to the whole model even when the validator is at the property level. The massive advantage of using a property level validator is that the error is set against the property itself instead of the class removing the requirement to use an Html.ValidationSummary. Since the validation error is set against the property correctly, your normal Html.ValidationFor Html.ValidationMessageFor helpers will pick up and display the error against the invalid form field.



它是在不久前编写的(使用 ASP.NET MVC 3),但在 .NET 4.6 框架中仍然有效。另外,我为 bool IsValid(object value) 实现了单元测试。方法。即使我只用 ValidationContext 覆盖该方法,测试也继续通过。范围。

关于.net - 实现自定义 ValidationAttribute 时应该覆盖哪个 IsValid 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38858392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com