.NET 8 Release New Data Annotation in ASP.NET Core C#

In this article, we will learn .NET 8 Release New Data Annotation in ASP.NET Core C#, along with explanations and code examples.

Data Annotations in ASP.NET Core are attributes and constraints that can be applied to an entity class or model properties to define validation rules.

  • Data Annotation attributes are used to control and validate input data either at the user interface level or at the database level.
  • Data annotations are a key feature of the .NET framework and can help make your code more efficient, easier to maintain, and more secure.

Required attribute

The Required attribute has been revised and has new parameters. In .NET 8 you can use DisallowAllDefaultValues property with the attribute so that the required attribute for the Guid member will work as expected.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

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

AllowedValues

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

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
        [AllowedValues("Computer","Eelectronics","Mechanical")]
        public  string DepartmentName { get; set; }
        
    }
}

BASE64String

The Base64string attribute ensures that the content is a complaint Base64 string.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
    [Base64String]
    public string Address { get; set; }     
    }
}

Range

Specify the numeric range constraints for the value of a property.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
    [Range(0, 100, MinimumIsExclusive = true, MaximumIsExclusive = true)]
    public int Age { get; set; }        
    }
}

Length

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

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
        [Length(8, 25)]
        public string Username { get; set; }
        
    }
}

DeniedValues

DeniedValues is a data annotation attribute in C# that specifies a list of values that are not allowed, it is the counterpart to allowedValues and prevents the specified values.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        [DeniedValues("Supervisor", "Operator")]
        public string UserRole { get; set; }
    }
}

See More: LINQ: Sort Multiple Columns using LINQ in C#

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments