I have two separate types:
public class Person
{
public string Name { get; set; }
public bool IsActive { get; set; }
public Contact ContactDetails { get; set; }
}
public class Contact
{
[RequiredIfActive]
public string Email { get; set; }
}
What I need is to perform conditional declarative validation of internal model field, based on some state of the parent model field - in this particular example an Email
has to be filled, if IsActive
option is enabled.
I do not want to reorganize these models taxonomy, while in the same time I need to use attribute-based approach. It seems that from within an attribute there is no access to the validation context of the parent model. How to reach or inject it there?
public class RequiredIfActiveAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
/* validationContext.ObjectInstance gives access to the current
Contact type, but is there any way of accessing Person type? */
Edit:
I know how conditional validation can be implemented using Fluent Validation, but I'm NOT asking about that (I don't need support regarding Fluent Validation). I'd like to know however, if exists any way to access parent model from inside System.ComponentModel.DataAnnotations.ValidationAttribute
.