4

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tien Dang
  • 41
  • 2
  • 3
  • Can you try to add validationb in razor? If(Status == 'Active') with validation else without ? – mike Jun 08 '21 at 08:27
  • Does [this](https://stackoverflow.com/questions/7390902/requiredif-conditional-validation-attribute) help? – Izzy Jun 08 '21 at 08:29
  • Or [this](https://stackoverflow.com/questions/20642328/how-to-put-conditional-required-attribute-into-class-property-to-work-with-web-a)? – Peter Csala Jun 08 '21 at 08:50
  • @Izzy That method could help somehow but I need the way for nested class get access to parent property, that's the point – Tien Dang Jun 08 '21 at 08:52

1 Answers1

3

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;
        }
    }

mike
  • 1,202
  • 1
  • 7
  • 20