开发者

Custom Validator Attribute exception in DataAnnotations

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

开发者_StackOverflow社区
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!


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜