我在一个类中使用模型验证,并且在一些属性中使用了属性。我已经按属性名称获取了属性名称,但它为我提供了属性中的所有属性,但我只需要出现错误的属性名称,例如,如果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
将包含string
值RequiredAttribute
。