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