menu

Sunday, September 18, 2016

Data Annotation

Is a way to validate business objects in easy and simplified manner.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace DataAnnotations
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer();
            try
            {
                cust.name = "";//It will throw exception
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            cust.name = "TestName";
            cust.number = "1234567890";//here length is 11 and requird max length is 10
            ValidationContext context = new ValidationContext(cust);
            List<ValidationResult> vResults = new List<ValidationResult>();
            bool isValid = Validator.TryValidateObject(cust, context, vResults, true);
            foreach (ValidationResult vResult in vResults)
           {
                Console.WriteLine(vResult.ErrorMessage);
            }
            Console.WriteLine("Customer Validation: {0}", isValid);
        }
    }
    public class Customer
    {
        private string _name;
        //Traditional way
        public string name
        {
            get { return _name; }
            set
            {
                if (value.Length == 0)
                {
                    throw new Exception("Name is required !");
                }
                _name = value;
            }
        }
        private string _number;
        //Through data annotation
        [Required(ErrorMessage = "Number is required !")]
        [StringLength(10, ErrorMessage = "Length should be <= 10")]
        public string number
        {
            get { return _number; }
            set { _number = value; }
        }
    }
}

No comments:

Post a Comment