Erin Aarested
Erin Aarested

Reputation: 473

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

Upvotes: 2

Views: 2619

Answers (1)

m.casey
m.casey

Reputation: 2599

According to the MSDN article, the TryValidateObject method will do the following:

This method evaluates each ValidationAttribute instance that is attached to the object type. It also checks whether each property that is marked with RequiredAttribute is provided. 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)

Upvotes: 4

Related Questions