| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Data Annotations in C#
Oct 26, 2024
3 min read

Data Annotations in C#

Sponsor this Newsletter

Data validation ensures that only correct and expected data reaches our databases, as user input can be unpredictable. We can use various validation methods, including Fluent Validation and Data Annotations to achieve this.

In this article, we’ll explore how to implement data annotations effectively in a web application.

Applying Validation Using Data Annotations

Data annotations allow us to apply validation by adding attributes to model properties. The System.ComponentModel.DataAnnotations namespace provides these attributes by default in .NET, with no additional setup needed.

Common Validation Attributes

Common validation attributes include:

  • [Required]

  • [StringLength]

  • [Range]

  • [RegularExpression]

  • [EmailAddress]

  • [Compare]

  • [MinLength]

  • [MaxLength]

  • [AllowedValues]

We’ll explore each of these with code examples.

Using Validation Attributes in C#

[Required]

Ensures that a property is not null or empty :

using System.ComponentModel.DataAnnotations;

namespace DataAnnotations.Models;

public sealed class User
{
    [Required]
    public string Name { get; set; }
    
    ... Other properties ...
}

This field is now required, and if a value is not provided, an error message will be displayed like this.

Data Annotations in C#

To customize the default error message, we can add the ErrorMessage attribute, like this :

public sealed class User
{
    [Required(ErrorMessage = "Name is required.")]
    public string Name { get; set; }
    
    ... Other properties ...
}

[StringLength]

Specifies the minimum and maximum length of a string property :

public sealed class User
{
  [StringLength(maximumLength:100,
   MinimumLength=6,
   ErrorMessage="Password must be between 6 and 100 characters")]
  public string Password { get; set; }
    
    ... Other properties ...
}

[Range]

Defines a numeric range for a property :

public sealed class User
{
     [Range(18, 65, ErrorMessage = "Age must be between 18 and 65")]
     public int Age { get; set; }
   
    ... Other properties ...
}

[RegularExpression]

Validates a property against a regular expression pattern :

public sealed class User
{
     [RegularExpression(@"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$",
     ErrorMessage = "Invalid email format.")]
     public string Email { get; set; }
   
    ... Other properties ...
}

[EmailAddress]

Validate a property whether it is a valid email or not:

public sealed class User
{
     [EmailAddress(ErrorMessage ="Email address is not valid")]
     public string Email { get; set; }
   
    ... Other properties ...
}

[Compare]

It compares the value of one property with another and makes sure both are the same:

public sealed class User
{
     [Required]
     [Compare("Password", 
     ErrorMessage = "Password and ConfirmPassword should be same")]
     public string ConfirmPassword { get; set; }

    [Required]
    public string Password { get; set; }
}

[MinLength] and [MaxLength]

Another way to specify the minimum and maximum length of a string or array type property :

public sealed class User
{
    [Required]
    [MinLength(4)]
    [MaxLength(20)]
    public string Name { get; set; }
    
    ... Other properties ...
}

[AllowedValues]

Gets the list of values allowed by this attribute :

public sealed class User
{
    [AllowedValues(UserTypes.Admin)]
    public UserTypes UserType { get; set; }
    
    ... Other properties ...
}

public enum UserTypes
{
    Admin,
    Customer
}

How validation is triggering

If you’re wondering how this validation is triggered, you’ll need to add asp-validation-for it to your HTML(View in my case for MVC)

 <div class="form-group">
     <label asp-for="Name" class="control-label"></label>
     <input asp-for="Name" class="form-control" />
     <span asp-validation-for="Name" class="text-danger"></span>
 </div>

Additional Purposes of Data Annotations

Data annotations can also serve additional purposes beyond validation, such as:

[Display]

Specifies how data, including name, description, and order, is displayed in the UI.

[DisplayFormat]

Specifies the format for displaying data, such as date and currency formats.

[DataType]

Provides additional type information, such as DataType.Date, DataType.Time, DataType.Currency, etc.

[Key]

Specifies that a property is the primary key of an entity.

[ForeignKey]

Specifies a foreign key relationship between entities.

This article was originally published at https://mwaseemzakir.substack.com/ on Oct 26, 2024 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.