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

标签 c# asp.net asp.net-core validationattribute

我正在尝试编写自己的 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/

相关文章:

使用 simpletcp NuGet 包的 C# 客户端/服务器聊天应用程序

c# - 以编程方式获取 Windows 操作系统版本

c# - 无法将窗口置于样式中 (WPF)

asp.net - asp.net 页面中的 css 粘性页脚

ASP.NET MVC 4 和 session 安全漏洞

c# - ASP.NET 5 MVC 6 通用存储库模式

c# - 将查询字符串参数附加到对象 URL 的最佳方法

c# - 尝试存储 ListView ID

c# - Entity Frameworks 插入已插入的相关项

multithreading - StackExchange Redis 超时以及如何在 .NET Core 中设置最小线程池数量?