New Data Annotation attributes with .NET 8

New Data Annotation attributes with .NET 8

With .NET 8, the System.ComponentModel.DataAnnotations Namespace has been revised and some new attributes have been added that have been requested by the community for some time and have only been implemented through custom implementations.

Required

The Required attribute has been revised and has new parameters. In addition to the normal mandatory validation, it is now also possible to exclude certain default values.

This is particularly useful for IDs that are simply mandatory, but it was still possible to set the struct default and Required was therefore virtually functionless for non-nullable props.

[Required(DisallowAllDefaultValues = true)]
public Guid MyId { get; set; }

However, the better option in this case is still implementation using Strong-Ids.

Range

The Range attribute has been extended so that it is now possible to specify whether the range values are exclusive, which simplifies declarations.

[Range(0, 100, MinimumIsExclusive = true, MaximumIsExclusive = true)]
public int Age { get; set; }

This means that the permitted range is now 1-99.

Length

The Length attribute has been extended so that the maximum length can now also be specified.

[Length(10, 20)]
public string Username { get; set; }

This means that the permitted length will now be a minimum of 10 characters and a maximum of 20 characters.

Base64String

The new Base64String attribute ensures that the content is a compliant Base64 string.

[Base64String]
public string Hash { get; set; }

This is particularly useful for validations, but should not be used for passwords - after all, passwords should always be stored in a one-way hash method including mechanisms such as salting - but never as Base64.

AllowedValues

AllowedValues is a new attribute that specifies which values are allowed for a string, for example

[AllowedValues("Batman", "Catwoman", "James Bond")]
public string Hero { get; set; }

DeniedValues

DeniedValues is the counterpart to AllowedValues and prevents the specified values

[DeniedValues("Admin", "Administrator")]
public string Username { get; set; }

Source Code Generator with Options

Data annotations are primarily known when used in the Entity Framework, but they can be used in many places, for example in Options.

In the case of options, data annotations are now inserted into the class via Source Code Generator, which speeds up validation overall and therefore also benefits the startup time of applications.