如何从c#中的属性中获取验证属性名称

  • 本文关键字:属性 获取 验证 c# winforms
  • 更新时间 :
  • 英文 :


我在一个类中使用模型验证,并且在一些属性中使用了属性。我已经按属性名称获取了属性名称,但它为我提供了属性中的所有属性,但我只需要出现错误的属性名称,例如,如果Required属性激发,那么它应该只给我Required属性名称,而不是所有属性。我将提前分享我的代码并表示感谢。

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
}                                                       
}

继续您在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

最新更新