Validation using DataAnnotations






4.76/5 (5 votes)
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:
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 |
|
Uses a custom method for validation. |
Specifies a particular type of data, such as e-mail address or phone number. |
|
Ensures that the value exists in an enumeration. |
|
Designates minimum and maximum constraints. |
|
Uses a regular expression to determine valid values. |
|
Specifies that a value must be provided. |
|
Designates maximum and minimum number of characters. |
|
Serves as base class for validation attributes. |
Sample Console Application
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.