Tuesday, 1 March 2016

Validate Data annotation attribute from C#



Validate Data annotation attribute from C# manually.

Create validation method :

public static IEnumerable<string> Validate(params object[] objects)
{
   foreach (var item in objects)
   {               
     PropertyInfo[] properties = item.GetType().GetProperties();

     foreach (var propertyInfo in properties)
     {
       object[] customAttributes = propertyInfo.GetCustomAttributes(
typeof(ValidationAttribute),
inherit: true);

       foreach (var customAttribute in customAttributes)
       {
         var validationAttribute = (ValidationAttribute)customAttribute;

         bool isValid = validationAttribute.IsValid(propertyInfo.GetValue(item,     
                                                   BindingFlags.GetProperty,
   null,
   null,
   null));

         if (!isValid)
         {
           yield return validationAttribute.ErrorMessage;
         }
       }
     }
   }
}

Add DTO class :

    public class TestClass1
    {
        [Required(ErrorMessage = "This field is required")]
        [EmailAddress(ErrorMessage = "Please enter valid email address")]
        public string Email { get; set; }

        [Range(0, 10, ErrorMessage = "Value between 0 to 10")]
        public int Num1 { get; set; }

        public TestClass2 TestClass2 { get; set; }
    }

    public class TestClass2
    {
        [Required(ErrorMessage = "FirstName is required")]
        public string FirstName { get; set; }
    }

Now use validation method in real code :

TestClass1 tc = new TestClass1();
            tc.Email = "AP@"; // Please enter valid email address
            tc.Num1 = 50; // Value between 0 to 10
            tc.TestClass2 = new TestClass2(); // FirstName is required

            var messages =  Validate(tc, tc.TestClass2);
            StringBuilder sb = new StringBuilder();
            foreach (var item in messages)
            {
                sb.AppendLine(item);
            }

No comments:

Post a comment