Click here to Skip to main content
15,896,201 members
Articles / Programming Languages / C#
Tip/Trick

Validation using DataAnnotations

Rate me:
Please Sign up or sign in to vote.
4.76/5 (5 votes)
22 Feb 2013CPOL 38.3K   413   10  
To use in WinForms.

Introduction   

In the programming world, validating data is most important then anything else. Programmers use there own logic to validate incoming and outgoing data. In .NET 4.0 Microsoft provides a very nice namespace called System.ComponentModel.DataAnnotations for doing validation. This type of validation for mostly used in MVC application but it can use this in any kind of application. 

Validation Attributes 

The System.ComponentModel.DataAnnotations namespace provides a list of attributes than can be placed on top of the property needed to be validated. Example:

C#
public class Employee
{
    [StringLength(7, MinimumLength = 5, ErrorMessage = "min 5 max 7")]
    public string Name { get; set; }
    [Required]
    public string Address { get; set; }
    [Required]
    public int? Age { get; set; }
} 

Following are the Types of Validation Attributes:

Validation Attribute

Description

CustomValidationAttribute

Uses a custom method for validation.

DataTypeAttribute

Specifies a particular type of data, such as e-mail address or phone number. 

EnumDataTypeAttribute

Ensures that the value exists in an enumeration.

RangeAttribute

Designates minimum and maximum constraints.

RegularExpressionAttribute

Uses a regular expression to determine valid values.

RequiredAttribute

Specifies that a value must be provided.

StringLengthAttribute

Designates maximum and minimum number of characters.

ValidationAttribute

Serves as base class for validation attributes.  

Sample Console Application 

C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PropertyValidation
{

    public class Employee
    {     
        private int m_IdNumber;
        private string m_FirstName;
        private string m_LastName;
        private string m_email;

        // Public properties.
        [Display(Name = "ID Number", Description = "Enter an integer between 0 and 99999.")]
        [Range(0, 99999)]
        public int IdNumber
        {
            get { return m_IdNumber; }
            set
            {
                Validator.ValidateProperty(value,
                    new ValidationContext(this, null, null) { MemberName = "IdNumber" });
                m_IdNumber = value;
            }
        }

        [Display(Name = "Name", Description = "First Name + Last Name.")]
        [Required(ErrorMessage = "First Name is required.")]
        [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage =
            "Numbers and special characters are not allowed in the name.")]
        public string FirstName
        {
            get { return m_FirstName; }

            set
            {
                Validator.ValidateProperty(value,
                    new ValidationContext(this, null, null) { MemberName = "FirstName" });
                m_FirstName = value;
            }
        }

        [Required(ErrorMessage = "Last Name is required.")]
        [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage =
            "Numbers and special characters are not allowed in the name.")]
        [StringLength(8, MinimumLength = 3, ErrorMessage =
            "Last name must be between 3 and 8 characters long.")]
        public string LastName
        {
            get { return m_LastName; }
            set
            {
                Validator.ValidateProperty(value,
                    new ValidationContext(this, null, null) { MemberName = "LastName" });
                m_LastName = value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();

            try
            {
                emp.IdNumber = 9999999;
            }
            catch (ValidationException ex)
            {
                Console.WriteLine(ex.Message);
            }
            try
            {
                emp.LastName = "k";

            }
            catch (ValidationException ex)
            {
                Console.WriteLine(ex.Message);
            }
            try
            {
                emp.FirstName = "5";
            }
            catch (ValidationException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.Read();

        }
    }
}

Output:

The field ID number must be between 0 and 99999.
Last name must be between 3 and 8 characters long.
Numbers and special characters are not allowed in the name.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --