I am using model validation in a class and I have used attributes in few properties. I have already get the attributes name by property name but it gives me all attributes from a property but I need only that attribute name which got error like ex- if Required attribute fires then it should give only me Required attribute name not all attributes.I am sharing my code and thanks in advance.
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
}
}