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.

4
  • Can you try to add validationb in razor? If(Status == 'Active') with validation else without ? Commented Jun 8, 2021 at 8:27
  • Does this help? Commented Jun 8, 2021 at 8:29
  • Or this? Commented Jun 8, 2021 at 8:50
  • @Izzy That method could help somehow but I need the way for nested class get access to parent property, that's the point Commented Jun 8, 2021 at 8:52

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I could do it but I want a solution for BE side
With this solution, I dont think we have a good way to handle this issue. Thank anyway. I decide to split it into piece for each case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.