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

时间:2010-08-27 17:28:56

标签: model-view-controller data-annotations validation

之前有没有人见过这个例外? 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);
        }

    }

谢谢!

1 个答案:

答案 0 :(得分:1)

您实际上应该为其中一种方法提供实施,而不是调用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)