0

I want to achieve the following, but it seems that its not possible:

[genericValidation  || specificValidation]
public int content{ get; set; }

I dont want to fuse both validations, because genericValidation is used in multiple places in the program(other classes), and would have to be copy/pasted on each specificValidation. And specific is only specific to this class so Im trying to keep specific and generic apart.

I want to avoid copy pasting the content of generic, into each specific validation. Given that this generic/specific "OR" happens in several classes.

Is there any way to achieve this?

luisluix
  • 547
  • 5
  • 17

1 Answers1

1

You can create SpecificValidationAttribute and inherit it from GenericValidationAttribute. For example

    public class GenericValidationAttribute: ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var obj = validationContext.ObjectInstance as IBaseObject;
            if(obj == null) return ValidationResult.Success;
            if(obj.content < 0)
               return new ValidationResult("Content have to be greater than zero!");
             return ValidationResult.Success;
        }
   }

    public class SpecificValidationAttribute: GenericValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var res = base.IsValid(value, validationContext);
            if(res != ValidationResult.Success) return res;

            // Do some specific validation
            // ---- 
            return ValidationResult.Success;
        }
    }