Search This Blog

Tuesday, April 5, 2016

Validate Data Models Using DataAnnotations Attributes C#

C# > System > ComponentModel > DataAnnotations

Provides attribute classes that are used to define metadata.

Example

Validate property class with range numbers



using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Forms;

namespace WindowsFormsApplication8
{
    public class Person
    {
        private int id;

        [Display(Name = "Person Id")]
        [Range(0, 1000)]
        public int Id
        {
            get { return id; }
            set
            {
                Validator.ValidateProperty(value,
                    new ValidationContext(this, null, null) { MemberName = "Id" });
                id = value;
            }
        }
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Person p = new Person();
            p.Id = 1;
            p.Id = 1001;
        }
    }
}