将类的属性传递给 ValidationAttribute

Tom*_*adi 2 c# asp.net validationattribute asp.net-core

我正在尝试编写自己的程序ValidationAttribute,我想将我的类的参数值传递给ValidationAttribute. 很简单,如果布尔属性是true,则顶部的属性ValidationAttribute不应该为 null 或为空。

我的课:

public class Test
{
    public bool Damage { get; set; }
    [CheckForNullOrEmpty(Damage)]
    public string DamageText { get; set; }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我的属性:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

pfx*_*pfx 6

您不应将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; }
}
Run Code Online (Sandbox Code Playgroud)
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;
    }
}
Run Code Online (Sandbox Code Playgroud)