简体   繁体   English

自定义数据注释属性未得到验证

[英]Custom data annotation attribute not being validated

I am trying to make a custom validation using data annotations. 我正在尝试使用数据注释进行自定义验证。 Trying to make the attribute, I have followed the question: How to create Custom Data Annotation Validators 在尝试创建属性时,我遵循了以下问题: 如何创建自定义数据注释验证器

My attribute looks like this 我的属性看起来像这样

internal class ExcludeDefaultAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return false;
    }
}

and the validation is called by: 并通过以下方式调用验证:

internal static class TypeValidator
{
    static public bool Validate(object item)
    {
        List<ValidationResult> results = new List<ValidationResult>();
        ValidationContext context = new ValidationContext(item);
        if (Validator.TryValidateObject(item, context, results))
        {
            return true;
        }
        else
        {
            string message = string.Format("Error validating item");
            throw new TypeInvalidException(results, message);
        }
    }
}

So, here is the issue. 因此,这就是问题所在。 My custom validation, currently, should always return false. 目前,我的自定义验证应始终返回false。 So validation should always fail. 因此,验证应始终失败。 However, whenever I try to validate an object that has this attribute on a field, it passes validation, which suggests that my custom validation attribute isn't being evaluated. 但是,每当我尝试验证在字段上具有此属性的对象时,它都会通过验证,这表明未在评估我的自定义验证属性。 I don't want to make any actual logic in the validation until I know it is actually running. 我不希望在验证中做任何实际的逻辑,直到我知道它实际上在运行。 Am I missing something? 我想念什么吗? All my research says I simply need to inherit from ValidationAttribute, but it isn't working. 我所有的研究都说我只需要从ValidationAttribute继承,但是它不起作用。

According to the MSDN article , the TryValidateObject method will do the following: 根据MSDN文章 ,TryValidateObject方法将执行以下操作:

This method evaluates each ValidationAttribute instance that is attached to the object type. 此方法评估附加到对象类型的每个ValidationAttribute实例。 It also checks whether each property that is marked with RequiredAttribute is provided. 它还检查是否提供了标有RequiredAttribute的每个属性。 It does not recursively validate the property values of the object. 它不会递归地验证对象的属性值。

I tested this and it behaved as advertised using the syntax provided. 我对此进行了测试,并使用提供的语法对其进行了宣传。

Edit 编辑

Per the comment below, using the following overload results in proper validation of all properties including those using custom attributes: 根据下面的评论,使用以下重载可以正确验证所有属性,包括使用自定义属性的属性:

TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults, bool validateAllProperties)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM