Conditional Validation for nested object with parent condition

Viewed 380

I have the following classes:

class A {
    [Required]
    public string Status { get; set; }
    public B b_instance { get; set; }
}

class B {
    **[RequiredIf("A.Status == 'Active'")**
    public string x { get; set; }
}

As above, I want class B has a validation with the condition: A.Status = 'Active' then class B has [Required] x, otherwise b_instance.x is not required.

1 Answers

If you use MVC you coud add extra validation in razor view :


@if (Model.Status == "Active")
{
    <input class="form-control" asp-for="..." required="required" />
}
else
{
    <input class="form-control" asp-for="..." />
}

If like you mentioned you need a solution for BE side you can try something with custom Validation Attribute :


 public class A
 {
      [Required]
      public string Status { get; set; }
      public StatusEnum StatusEnum { get; set; }
      public B b_instance { get; set; }
    }

    public enum StatusEnum
    {
        Active = 1,
        Deactivated = 2,
    }

    public class B : A 
    {
        [RequiredIf("Status", StatusEnum.Active , ErrorMessage = "...")]
        public string x { get; set; }
    }

    public class RequiredIfAttribute : ValidationAttribute
    {
        public string PropertyName { get; set; }
        public object Value { get; set; }

        public RequiredIfAttribute(string propertyName, object value, string errorMessage = "")
        {
            PropertyName = propertyName;
            ErrorMessage = errorMessage;
            Value = value;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var instance = validationContext.ObjectInstance;
            var type = instance.GetType();
            var propertyValue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (propertyValue .ToString() == Value.ToString() && value == null)
            {
                return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }
    }

Related