具有父条件的嵌套对象的条件验证



我有以下类:

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

如上所述,我希望类B具有条件为:a.状态="活动"的验证,则类B具有[必需]x,否则不需要B_instance.x。

如果你使用MVC,你可以在剃刀视图中添加额外的验证:


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

如果像你提到的那样,你需要一个BE方面的解决方案,你可以尝试一些自定义验证属性:


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

相关内容

  • 没有找到相关文章

最新更新