gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:55:45 24 4
gpt4 key购买 nike

我有以下类(class):

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.Status = 'Active' 然后 B 类具有 [Required] x,否则不需要 b_instance.x。

最佳答案

如果您使用 MVC,您可以在 razor View 中添加额外的验证:


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

关于c# - 具有父条件的嵌套对象的条件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67883976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com