DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Using AllowedValues and DeniedValues in .NET 8

.NET 8 introduced new attributes, AllowedValues and DeniedValues, as part of the System.ComponentModel.DataAnnotations namespace. These attributes simplify input validation by specifying which values are permitted and which are not for your API parameters.
The code sample is available in the comments.

What are AllowedValues and DeniedValues?

  • AllowedValues: Ensures that only specified values are accepted.
  • DeniedValues: Ensures that specified values are not accepted.

           [AllowedValues("Red", "Yellow", "Green")]
           [DeniedValues("Black", "White")]
           public string? AlertValue { get; set; }

Enter fullscreen mode Exit fullscreen mode

Explanation

  • AlertValue string: Uses AllowedValues to ensure only "Red", "Yellow", or "Green" are accepted. Uses DeniedValues to reject "Black" and "White".

Conclusion

Using AllowedValues and DeniedValues attributes in .NET 8 simplifies input validation in your API, ensuring that only valid values are accepted and invalid ones are rejected. This enhances the robustness and reliability of your application.

Top comments (1)

Collapse
 
moh_moh701 profile image
mohamed Tayel