DataAnnotations 中的自定义验证器属性异常

发布于 2024-09-16 18:14:02 字数 872 浏览 6 评论 0原文

以前有人见过这个异常吗? Google 或 Bing 的结果绝对很少。

IsValid(object value) has not been implemented by this class.  
The preferred entry point is GetValidationResult() and classes should override 
IsValid(object value, ValidationContext context).

这是自定义验证器:

public class PriceAttribute : ValidationAttribute
    {
        public string Id { get; set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //I think this definition for IsValid is in DataAnnotations 4.0
            return base.IsValid(value, validationContext);
        }

        public override bool IsValid(object value)
        {
            //This I think is the older definition. Not sure why it expects this
            return base.IsValid(value);
        }

    }

谢谢!

Has anyone seen this exception before? Google or Bing has absolutely very few results.

IsValid(object value) has not been implemented by this class.  
The preferred entry point is GetValidationResult() and classes should override 
IsValid(object value, ValidationContext context).

Here's the custom validator:

public class PriceAttribute : ValidationAttribute
    {
        public string Id { get; set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //I think this definition for IsValid is in DataAnnotations 4.0
            return base.IsValid(value, validationContext);
        }

        public override bool IsValid(object value)
        {
            //This I think is the older definition. Not sure why it expects this
            return base.IsValid(value);
        }

    }

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

会发光的星星闪亮亮i 2024-09-23 18:14:02

您实际上应该为这些方法之一提供实现,而不是调用 base.IsValid(value)base.IsValid(value,validationContext)

public class PriceAttribute : ValidationAttribute
{
    public string Id { get; set; }

    public override bool IsValid(object value)
    {
        return Id == "120"; // <-- put your condition here
    }
}

如果可以在不检查上下文的其他值的情况下验证该值,则只需重写 IsValid(object value) 即可。

You should actually provide an implementation for one of those methods instead of calling base.IsValid(value) or base.IsValid(value, validationContext).

public class PriceAttribute : ValidationAttribute
{
    public string Id { get; set; }

    public override bool IsValid(object value)
    {
        return Id == "120"; // <-- put your condition here
    }
}

If the value can be validated without examining other values of the context, you can just override IsValid(object value).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文