How to get a validating attribute name from a property in c#

Prashant Sharma 66 Reputation points
2021-04-14T19:50:53.9+00:00

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
    }  

}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,967 questions
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,322 questions
No comments
{count} votes

Accepted answer
  1. Viorel 82,741 Reputation points
    2021-04-14T20:16:58.717+00:00

    Try identifying the attributes by error messages:

    var Validation = type
       .GetProperty( PropName )
       .GetCustomAttributes( false )
       .OfType<ValidationAttribute>( )
       .Where( a => a.ErrorMessage == error.ErrorMessage )
       .ToDictionary( a => a.GetType( ).Name, a => a );
    
    No comments

0 additional answers

Sort by: Most helpful