khaled saleh
khaled saleh

Reputation: 518

How to ignore custom attribute of class in one of its object(s)

I have created custom attribute that is used on Translation class, which is applied as following:

[ValidateTranslationDictionary]
public class Translations : Dictionary<string, string>{  }

The attribute code is:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public class ValidateTranslationDictionaryAttribute : ValidationAttribute
{
    public ValidateTranslationDictionaryAttribute() : base() { }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        DoSomeValidationHere(); //....
        return ValidationResult.Success; //for example
    }
}

My default scenario is to apply the validation attribute on all objects of the Translation class (currently work perfectly),

but in some cases I need to skip this validation on some object, example:

public class Test{
    public Translations WithValidation{ get; set; }
    public Translations WithoutValidation{ get; set; }
}

There is a way to not run the validation on WithoutValidation property of Test class but keep it on the others objects?

Also I tried to add boolean to the attribute as flag to run the validation, and put the attribute on both class and property, but the attribute validator run 2 times, first from property, and the second call from the class

hint: can I add another attribute called for example IgnoreValidationAttribute , and make it skip ValidateTranslationDictionary attribute?

Upvotes: 0

Views: 768

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

So the thing is that Translations object does not really require validation, at least not all of the time.

Why not approach this another way.

  • Leave the Translations class as it is without the attribute.
  • Then apply the attribute on attribute level
public class Test{
    [ValidateTranslationDictionary]
    public Translations WithValidation{ get; set; }
    public Translations WithoutValidation{ get; set; }
}

And if you need the exact same class with validations, then

[ValidateTranslationDictionary]
public class ValidTranslations: Translations 

Upvotes: 1

Related Questions