【问题标题】:How to get a validating attribute name from a property in c#如何从 C# 中的属性获取验证属性名称
【发布时间】:2021-04-15 04:48:12
【问题描述】:

我在一个类中使用模型验证,并且我在几个属性中使用了属性。我已经通过属性名称获取了属性名称,但它为我提供了一个属性的所有属性,但我只需要那个出现错误的属性名称,例如 ex-如果必需属性触发,那么它应该只给我必需的属性名称而不是所有属性。我我正在分享我的代码,并提前致谢。

public class ProductModel
{
    [PrimaryKey, AutoIncrement]
    public int ProductID { get; set; }
    
    [Required(ErrorMessage = "Please Enter Product Name")]
    public string ProductName { get; set; }

    [Required(ErrorMessage = "Please Enter Quantity")]
    [RegularExpression("^[0-9]*$", ErrorMessage = "Please Enter Numeric Values in Quantity")]
    [Range(1, int.MaxValue, ErrorMessage = "Please enter a value greater than 0")]
    public string Quantity { get; set; }
}

public static bool IsFormValid()
{
    var model="ProductModel";     
    var errors = new List<ValidationResult>();
    var context = new ValidationContext(model);
    bool isValid = Validator.TryValidateObject(model, context, errors, true);
    
    if (isValid == false)
    {
        ShowValidationFields(errors, model);
    }
    return errors.Count() == 0;
}

private static void ShowValidationFields(List<ValidationResult> errors, object model)
{
   
    if (model == null) { return; }
   
    foreach (var error in errors)
    {          
        var PropName = error.MemberNames.FirstOrDefault().ToString();
        Type type = model.GetType().UnderlyingSystemType;
        
        var Validation = type.GetProperty(PropName).GetCustomAttributes(false)
                    .ToDictionary(a => a.GetType().Name, a => a);

        --here i am getting all attributes name  assign in a property
    }                                                       
}

【问题讨论】:

  • 我不确定我是否完全理解这个问题,但 errors 集合包含“违规”属性。你能用它来检索验证失败的特定属性吗?
  • 我认为他只想要有问题的属性名称,但反射不会这样做。
  • @ShaiCohen 是的,错误集合只包含有问题的属性,是的,我可以获得属性的名称和属性错误消息,但我也想获得属性名称,例如 (Required,RegularExpression)
  • @insane_developer 是的,你说得对,我只想冒犯属性名称,但 Validation 给了我所有属性名称
  • @PrashantSharma ValidationResult 为您提供有验证错误的成员。它没有为您提供触发错误的显式属性。除了列出其所有属性之外,对该成员使用反射不会为您做任何事情。

标签: c# winforms


【解决方案1】:

ShowValidationFields 继续您的工作。

仅从相关属性中检索 ValidationAttributes

var validationAttributes = type.GetProperty(PropName).GetCustomAttributes<ValidationAttribute>();

然后,要查找有错误的ValidationAttribute,您可以(仅)对ValidationResult (error) 和ValidationAttribute 之间的错误消息进行匹配。

var validationAttributeWithError = 
    validationAttributes.FirstOrDefault(o => o.ErrorMessage == error.ErrorMessage);

var attributeName = validationAttributeWithError.GetType().Name;

如果ProductName 上的RequiredAttribute 有错误,attributeName 将包含stringRequiredAttribute

【讨论】:

  • validationAttributeWithError 我只得到了 errormsg 但仍然没有得到属性名称,并且在 **validationAttributes ** 我得到了所有属性
  • @PrashantSharma 用检索属性名称的方式更新了我的帖子。
  • @PrashantSharma 很高兴!
猜你喜欢
  • 2010-09-28
  • 2018-11-16
  • 2017-01-13
  • 1970-01-01
  • 2012-01-08
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
相关资源
最近更新 更多