How To Manually validate with Data Annotations
C# How To

How To Manually validate with Data Annotations

Mishel Shaji
Mishel Shaji

Introduction

Validation is the first and most important step in securing an application. It prevents the application from processing unwanted inputs that may produce unpredictable results.

Fortunately, in .NET, we have a namespace named DataAnnotationsthat has several classes and Attributes to help us to validate data. You might be already familiar with this namespace if you have developed MVC apps in .NET.

In this post, I’ll explain how to validate class objects in C# using DataAnnotations.

Validating using DataAnnotation

To keep the code simple and short as much as possible, let’s start by creating a Console application.

First, create a new class named User and add some properties to it. We’ll be validating an object of this class.

class User
{
    public string email { get; set; }

    public string name { get; set; }

    public int age { get; set; }
}

To use DataAnnotations namespace in our application, we must add a reference to System.ComponentModel.DataAnnotations assembly. You can do this by:

  1. Go to Solution Explorer.
  2. Right-click on References and choose Add Reference.
  3. In the window that appears, Select Assembles from the left side and search for System.ComponentModel.DataAnnotations.
  4. Select the item (make sure there is a checkmark on it’s left) and click OK.

Now, let’s add some validation attributes to the properties of our class.

using System.ComponentModel.DataAnnotations;
namespace MyConsoleApp
{    
    class User
    {
        [Required]
        [EmailAddress]
        public string email { get; set; }

        [MinLength(3)]
        [MaxLength(15)]
        public string name { get; set; }

        [Required]
        [Range(1, 100)]
        public int age { get; set; }
    }
}

Next, we need to create an instance of the class and a ValidationContext to describe the context in which the validation should be performed.

class Program
{
    static void Main(string[] args)
    {
        User u = new User();

        // Email should be in correct format
        u.email = "a_wrong_email";

        // Age should be less than 100
        u.age = 150;

        var ctx = new ValidationContext(u);
    }
 }

And we can validate the object using TryValidateObject() method of Validator class.

class Program
{
    static void Main(string[] args)
    {
        User u = new User();

        // Email should be in correct format
        u.email = "a_wrong_email";

        // Age should be less than 100
        u.age = 150;

        var ctx = new ValidationContext(u);

        // A list to hold the validation result.
        var results = new List<ValidationResult>();

        if (!Validator.TryValidateObject(u, ctx, results, true))
        {
            foreach (var errors in results)
            {
                Console.WriteLine("Error {0}", errors);
                return;
            }
        }
    }
 }

Note that the fourth parameter of TryValidateObject is set to true. If it is set to false, only the first property will be validated.

If you enjoyed this post, let me know in the comments below.