What’s new with Data Annotation in .NET 8

Introduction

Data annotations are basically used for model validation. These are the attributes that can be applied to the members of the class to specify some validation rules. In this blog, we will discuss one of the enhancements in data annotation for the class member validation in .NET 8.

Enhancement in Required attribute

Before .NET 8, even though we decorate the required attribute for the Guid member, it will apply the default value, consider below API Action. 

[HttpPost]
public IActionResult Post([FromBody] Employee employee) 
{
    if (!ModelState.IsValid)
    {
        return BadRequest();
    }
    return Ok(employee);
}

Model

public class Employee
{
    [Required]
    public Guid Id { get; set; }
}

"Id" is a required field, but if you not passing the Id from the request payload it will take the default value, which is unexpected because the Guid is a Struct type.

From Swagger testing the result, 

Data Annotation in .NET 8

Empty request payload 

Data Annotation in .NET 8

Unexpected output with the default value for "id". 

To make it work as expected, we need to update the Guid as nullable, as given below. 

public class Employee
{
    [Required]
    public Guid? Id { get; set; }
}

From .NET 8 you can use DisallowAllDefaultValues property with the attribute so that the required attribute for the Guid member will work as expected. 

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

From Swagger testing the result,  

Data Annotation in .NET 8

Now you will get a proper validation error as expected. 

Conclusion

We have seen a minor enhancement in the data annotation required attribute for the class members with .NET 8. We will see more useful features from .NET 8 in my upcoming blogs.