我正在尝试编写我自己的ValidationAttribute,我想将类的参数的值传递给ValidationAttribute。非常简单,如果布尔属性为true,则顶部为ValidationAttribute的属性不应为空或空。
我的班级:
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。传递该属性值的解决方案是什么?
发布于 2020-05-20 21:26:46
与其将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;
}
}https://stackoverflow.com/questions/61922439
复制相似问题