C# 将类的属性传递给ValidationAttribute
我正在尝试编写自己的C# 将类的属性传递给ValidationAttribute,c#,asp.net,asp.net-core,validationattribute,C#,Asp.net,Asp.net Core,Validationattribute,我正在尝试编写自己的ValidationAttribute,希望将类的参数值传递给ValidationAttribute。非常简单,如果布尔属性为true,则顶部带有ValidationAttribute的属性不应为null或空 我的班级: public class Test { public bool Damage { get; set; } [CheckForNullOrEmpty(Damage)] public string DamageText { get; se
ValidationAttribute
,希望将类的参数值传递给ValidationAttribute
。非常简单,如果布尔属性为true
,则顶部带有ValidationAttribute
的属性不应为null或空
我的班级:
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
值传递给checkforNullorEmptyaAttribute
;在属性中,您可以从正在验证的对象实例中检索此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;
}
}