gpt4 book ai didi

c# - 将类的属性传递给 ValidationAttribute

转载 作者:行者123 更新时间:2023-12-02 19:30:21 25 4
gpt4 key购买 nike

我正在尝试编写自己的 ValidationAttribute,我想将我的类的参数值传递给 ValidationAttribute。很简单,如果 bool 属性为 true,则顶部带有 ValidationAttribute 的属性不应为 null 或为空。

我的类(class):

public class Test
{
public bool Damage { get; set; }
[CheckForNullOrEmpty(Damage)]
public string DamageText { get; set; }
...
}

我的属性:

public class CheckForNullOrEmpty: ValidationAttribute
{
private readonly bool _damage;

public RequiredForWanrnleuchte(bool damage)
{
_damage = damage;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string damageText = validationContext.ObjectType.GetProperty(validationContext.MemberName).GetValue(validationContext.ObjectInstance).ToString();
if (_damage == true && string.IsNullOrEmpty(damageText))
return new ValidationResult(ErrorMessage);

return ValidationResult.Success;
}
}

但是,我不能像那样简单地将类内的属性传递给 ValidationAttribute。传递该属性值的解决方案是什么?

最佳答案

您应该传递相应属性的名称,而不是将 bool 值传递给 CheckForNullOrEmptyAttribute;在该属性中,您随后可以从正在验证的对象实例中检索此 bool 值。

下面的 CheckForNullOrEmptyAttribute 可以应用于您的模型,如此处所示。

public class Test
{
public bool Damage { get; set; }

[CheckForNullOrEmpty(nameof(Damage))] // Pass the name of the property.
public string DamageText { get; set; }
}

public class CheckForNullOrEmptyAttribute : ValidationAttribute
{
public CheckForNullOrEmptyAttribute(string propertyName)
{
PropertyName = propertyName;
}

public string PropertyName { get; }

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var hasValue = !string.IsNullOrEmpty(value as string);
if (hasValue)
{
return ValidationResult.Success;
}

// Retrieve the boolean value.
var isRequired =
Convert.ToBoolean(
validationContext.ObjectInstance
.GetType()
.GetProperty(PropertyName)
.GetValue(validationContext.ObjectInstance)
);
if (isRequired)
{
return new ValidationResult(ErrorMessage);
}

return ValidationResult.Success;
}
}

关于c# - 将类的属性传递给 ValidationAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61922439/

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