What and why IValidatebleObject in C#

3 minute read

IValidatableObject is an interface in C# that defines a method named Validate, which enables an object to perform custom validation logic. When you implement this interface in a class, you can add custom validation logic to that class.

The Validate method defined in IValidatableObject takes no parameters and returns an IEnumerable. The method can perform any validation logic and return an enumerable collection of ValidationResult objects that represent the validation errors or warnings. If the object is valid, the Validate method should return an empty collection.

The Validate method is called automatically when you use the Validator class to validate an object. You can also call the Validate method directly if you want to perform custom validation logic.

Here is an example of a class that implements IValidatableObject.

Step 1: Create a console application and a class name Employee as follows.

Employee.cs


using System.ComponentModel.DataAnnotations;

namespace IValidatebleObjectDemo
{
    public class Employee : IValidatableObject
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Status { get; set; }
        public int DesignationId { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if(Id <= 0)
            {
                yield return new ValidationResult("Employee Id is a required filed!", new[] {"Id"});
            }

            if (String.IsNullOrEmpty(Name))
            {
                yield return new ValidationResult("Employee Name is a required field!", new[] { "Name" });
            }
        }
    }
}

The above code defines an Employee class that implements the IValidatableObject interface in C#. The Employee class has four properties - Id, Name, Status, and DesignationId.

The Validate method is used to perform custom validation logic on the Employee object. The method checks if the Id property is less than or equal to zero and if the Name property is null or empty. If either of these conditions is true, the method returns a ValidationResult object that contains an error message and the name of the property that failed validation.

The ValidationResult class is part of the System.ComponentModel.DataAnnotations namespace, which provides a set of validation attributes and classes that can be used to validate data in a .NET application. In this case, the ValidationResult class is used to represent the result of a validation check, and the yield return statement is used to return the ValidationResult object to the caller. By using yield return instead of adding the validation results to a collection and returning the collection at the end of the method, the Validate method can return the validation results one at a time as they are generated, without needing to generate the entire sequence of results up front.

Step 2: Validate Employee class using the following code.

Program.cs


using IValidatebleObjectDemo;
using System.ComponentModel.DataAnnotations;

var result = new List<ValidationResult>();
bool validateAllProperties = false;
bool isValid = false;

var employee = new Employee()
{
    Id = 1,
    Name = "Mahedee Hasan",
    Status = true,
    DesignationId = 1
};


isValid = Validator.TryValidateObject(employee, new ValidationContext(employee, null, null), 
    result, validateAllProperties);

var employee2 = new Employee()
{
    Id = -1,
    Name = null,
    Status = true,
    DesignationId = 1
};

isValid = Validator.TryValidateObject(employee2, new ValidationContext(employee2, null, null), 
    result, validateAllProperties);   

The code block of step 2 performs object validation using the Validator.TryValidateObject method from the System.ComponentModel.DataAnnotations namespace.

Here, List object is created to store any validation errors that are generated during the validation process.

The Validator.TryValidateObject method is then called with the employee object, a new instance of ValidationContext, the result list, and the validateAllProperties boolean variable. This method attempts to validate the employee object based on the validation rules defined in the Employee class’s Validate method. Here you will see employee object is valid and there is no element in result list and isValid is ture.

But, second instance of the Employee class with some invalid data and calls the Validator.TryValidateObject method again with this object. You will see two error in the result list and isValid is false.

Overall, this code demonstrates how to use IValidatebleObject to perform object validation in C# application using validation rules defined in the object’s validation method.

Source code

Tags:

Categories:

Updated: