question

PrashantSharma-9315 avatar image
0 Votes"
PrashantSharma-9315 asked Viorel-1 answered

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

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
     }  
                                                        
 }
dotnet-csharpwindows-forms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered

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 );


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.