Saturday, February 4, 2017

DataAnnotation

DataAnnotation is used for validation. It supports following propperties

  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text we want used on form fields and validation messages
  • StringLength – Defines a maximum length for a string field
  • Range – Gives a maximum and minimum value for a numeric field
  • Bind – Lists fields to exclude or include when binding parameter or form values to model properties
  • ScaffoldColumn – Allows hiding fields from editor forms
Example


 class MainClass
    {
        public void CopyDataByMapper()
        {
            Person objPerson = new Person();           
            objPerson.FirstName = "";
            objPerson.LastName = "Ahmad";

            var context = new ValidationContext(objPerson,null,null);

            var result = new List();

            bool IsValid = Validator.TryValidateObject(objPerson,context,result,true);

            Console.WriteLine(IsValid);
            foreach (var item in result)
            {
                Console.WriteLine(item.ErrorMessage);
            }

            Console.ReadKey();
        }
    }

    class Person
    {

        [Required(ErrorMessage = "FirstName is required")]
        [StringLength(20)]
        public String FirstName { get; set; }
        public String LastName { get; set; }
    }

No comments:

Followers

Link