New Data Annotations in .NET 8

DotNet Full Stack Dev
4 min readJun 30, 2024

--

Data Annotations are a way to provide metadata for your classes in .NET. They are used extensively in ASP.NET for model validation, defining database schemas, and more. With the release of .NET 8, several new data annotations have been introduced to enhance the capabilities of model validation and metadata definition. In this blog, we’ll explore these new annotations, their use cases, and provide code snippets to demonstrate how they work.

Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. Uncover more by visiting our https://dotnet-fullstack-dev.blogspot.com reach out for further information.

Introduction to Data Annotations

Data Annotations are attributes you can apply to your classes and properties to enforce validation rules, specify formatting options, and define relationships between entities. They are commonly used in ASP.NET MVC and ASP.NET Core applications for model validation and in Entity Framework for database schema definitions.

Here’s a quick example of a class with some basic data annotations:

public class Product
{
[Key]
public int Id { get; set; }

[Required]
[StringLength(100)]
public string Name { get; set; }

[Range(0.01, 9999.99)]
public decimal Price { get; set; }
}

In this example:

  • Key specifies the primary key.
  • Required ensures the Name property is not null or empty.
  • StringLength sets the maximum length for the Name property.
  • Range restricts the Price property to a range of values.

New Data Annotations in .NET 8

1. MinLength and MaxLength for Collections

.NET 8 introduces MinLength and MaxLength annotations for collections. These annotations allow you to specify the minimum and maximum number of elements in a collection.

Example

public class Order
{
[Key]
public int OrderId { get; set; }

[Required]
[MinLength(1, ErrorMessage = "An order must have at least one item.")]
[MaxLength(100, ErrorMessage = "An order cannot have more than 100 items.")]
public List<OrderItem> Items { get; set; }
}

public class OrderItem
{
[Required]
public string ProductName { get; set; }

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

In this example:

  • MinLength ensures that an order has at least one item.
  • MaxLength limits the number of items in an order to 100.

2. Contains for Strings

The Contains annotation allows you to specify a substring that must be present in a string property.

Example

public class User
{
[Key]
public int UserId { get; set; }

[Required]
[Contains("@", ErrorMessage = "Email must contain '@'.")]
public string Email { get; set; }
}

In this example:

  • Contains ensures that the Email property contains an '@' character.

3. FileExtensions for File Uploads

The FileExtensions annotation allows you to restrict the allowed file extensions for file uploads.

Example

public class FileUpload
{
[Key]
public int FileId { get; set; }

[Required]
[FileExtensions(Extensions = "jpg,png,pdf", ErrorMessage = "Only .jpg, .png, and .pdf files are allowed.")]
public IFormFile UploadedFile { get; set; }
}

In this example:

  • FileExtensions restricts the allowed file types to .jpg, .png, and .pdf.

4. CreditCard Validation

The CreditCard annotation is used to validate credit card numbers.

Example

public class Payment
{
[Key]
public int PaymentId { get; set; }

[Required]
[CreditCard(ErrorMessage = "Invalid credit card number.")]
public string CreditCardNumber { get; set; }
}

In this example:

  • CreditCard validates that the CreditCardNumber property contains a valid credit card number.

5. EmailAddress and PhoneNumber Annotations

These annotations provide a simple way to validate email addresses and phone numbers.

Example

public class Contact
{
[Key]
public int ContactId { get; set; }

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

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

In this example:

  • EmailAddress validates that the Email property contains a valid email address.
  • Phone validates that the PhoneNumber property contains a valid phone number.

Sample .NET Core Application

Here is a complete example demonstrating the use of these new annotations in a simple ASP.NET Core application:

using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

public class Product
{
[Key]
public int Id { get; set; }

[Required]
[StringLength(100)]
public string Name { get; set; }

[Range(0.01, 9999.99)]
public decimal Price { get; set; }

[MinLength(1, ErrorMessage = "At least one category is required.")]
[MaxLength(5, ErrorMessage = "A maximum of 5 categories is allowed.")]
public List<string> Categories { get; set; }
}

public class ProductController : Controller
{
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save the product to the database
return Ok("Product created successfully!");
}
else
{
return BadRequest(ModelState);
}
}
}

In this example:

  • The Product class uses various data annotations to enforce validation rules.
  • The ProductController uses model validation to ensure that the product data is valid before saving it to the database.

By incorporating these new data annotations into your .NET applications, you can enhance your data validation and improve the robustness of your application.

Conclusion

With .NET 8, data annotations have become even more powerful and flexible. The new annotations for collections, strings, file uploads, and specific types like credit card numbers, email addresses, and phone numbers make it easier to enforce validation rules and improve data integrity in your applications.

By leveraging these new annotations, you can write cleaner, more maintainable code, and ensure that your data meets the necessary validation criteria before it reaches your business logic or database.

--

--

DotNet Full Stack Dev
DotNet Full Stack Dev

Written by DotNet Full Stack Dev

Join me to master .NET Full Stack Development & boost your skills by 1% daily with insights, examples, and techniques! https://dotnet-fullstack-dev.blogspot.com

No responses yet