Member-only story

.NET 8.0 ๐——๐—ฎ๐˜๐—ฎ ๐—”๐—ป๐—ป๐—ผ๐˜๐—ฎ๐˜๐—ถ๐—ผ๐—ป๐˜€ ๐ŸšฉComplete Example with C#

R M Shahidul Islam Shahed
3 min readAug 17, 2024

โญ .NET 8 introduces a range of new data annotations that enhance data validation, making it simpler to enforce data integrity and business rules.

.NET 8.0 ๐——๐—ฎ๐˜๐—ฎ ๐—”๐—ป๐—ป๐—ผ๐˜๐—ฎ๐˜๐—ถ๐—ผ๐—ป๐˜€ ๐ŸšฉComplete Example with C#

โœ… Length Attribute: Ensures that string or collection lengths fall within a specified range.

โœ… Range Attribute with Minimum/Maximum Exclusivity: Validates numeric ranges with optional exclusivity settings.

โœ… Base64String Attribute: Confirms that a string is a valid Base64 encoded representation.

โœ… Allowed Values Attribute: Restricts a property to a set of predefined values.

โœ… Denied Values Attribute: Ensures that a property does not include specific values.

๐Ÿ”ฅ These new annotations significantly boost the reliability, maintainability, and security of .NET applications by offering an easy yet powerful approach to enforcing data integrity and validation rules.

Hereโ€™s a simple example of using Data Annotations in C# with .NET 8.0 to define validation rules for a model class:

.NET 8.0 ๐——๐—ฎ๐˜๐—ฎ ๐—”๐—ป๐—ป๐—ผ๐˜๐—ฎ๐˜๐—ถ๐—ผ๐—ป๐˜€ ๐ŸšฉComplete Example with C#

For Copy Code:

using System.ComponentModel.DataAnnotations;

namespace Console_Test
{
public class User
{
public int Id { get; set; }

[Required(ErrorMessage = "Username is required.")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Username must be between 3 and 50 characters.")]
public string Username { get; set; }

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

[Required(ErrorMessage = "Password is required.")]
[DataType(DataType.Password)]
[StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be between 6 and 100 characters.")]
public string Password { get; set; }

[Compare("Password", ErrorMessage = "Passwords do not match.")]
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }

[Range(18, 120, ErrorMessage = "Age must be between 18 and 120.")]โ€ฆ

Create an account to read the full story.

The author made this story available to Medium members only.
If youโ€™re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response