Data Validation in C# (.NET): Libraries and Approaches

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Data Validation in C# (.NET): A Complete Guide with Examples



Data validation is one of the key aspects of developing reliable applications in C# within the .NET ecosystem. It ensures that incoming data meets specified rules, preventing errors, vulnerabilities, and incorrect system states. In this article, we will thoroughly examine the main libraries and tools for validation in .NET, including built-in mechanisms and popular third-party solutions.



Why is Data Validation Important?

Without validation, an application can receive:

  • Incorrect data types (e.g., a string instead of a number).
  • Values outside allowed ranges (negative age, non-existent email).
  • SQL injections, XSS attacks, and other security threats.
  • Violations of business logic (an order without items, an empty username).

Using structured approaches to validation makes code cleaner, more testable, and more secure.



1. Built-in Validation: Data Annotations (System.ComponentModel.DataAnnotations)

The simplest and most common method is using attributes from the System.ComponentModel.DataAnnotations namespace. This approach is ideal for models in ASP.NET Core MVC, Web API, and Entity Framework.



Example model with attributes:

using System.ComponentModel.DataAnnotations;

public class User{ [Required(ErrorMessage = "Name is required")] [StringLength(50, MinimumLength = 2, ErrorMessage = "Name must be between 2 and 50 characters")] public string Name { get; set; }

[Required] [EmailAddress(ErrorMessage = "Invalid email")] public string Email { get; set; }

[Range(1, 120, ErrorMessage = "Age must be between 1 and 120")] public int Age { get; set; }

[Phone(ErrorMessage = "Invalid phone number")] public string Phone { get; set; }}


Programmatic model validation:

var user = new User { Name = "A", Email = "invalid", Age = 200 };var context = new ValidationContext(user);var results = new List<ValidationResult>();

bool isValid = Validator.TryValidateObject(user, context, results, true);

if (!isValid){ foreach (var error in results) { Console.WriteLine(error.ErrorMessage); }}


Advantages: simplicity, built-in support in ASP.NET Core, automatic validation at the controller level.

Disadvantages: limited flexibility, attributes are tightly coupled to the model, complex business rules are difficult to implement.



2. FluentValidation — Flexible and Expressive Validation

The FluentValidation library is the most popular third-party tool for validation in .NET. It allows you to move validation rules into separate classes, supports method chaining, custom messages, and complex conditions.



Installation via NuGet: Install-Package FluentValidation



Example validator:

using FluentValidation;

public class UserValidator : AbstractValidator<User>{ public UserValidator() { RuleFor(u => u.Name) .NotEmpty().WithMessage("Name cannot be empty") .Length(2, 50).WithMessage("Name length must be between 2 and 50 characters");

RuleFor(u => u.Email) .NotEmpty() .EmailAddress().WithMessage("Invalid email format");

RuleFor(u => u.Age) .InclusiveBetween(1, 120).WithMessage("Age is out of range");

// Custom rule RuleFor(u => u.Phone) .Matches(@"^\\+?[1-9]\\d{1,14}$").When(u => !string.IsNullOrEmpty(u.Phone)) .WithMessage("Phone number in international format"); }}


Use

Recommendations