DEV Community

mohamed Tayel
mohamed Tayel

Posted on • Edited on

Using AllowedValues and DeniedValues in .NET 8

.NET 8 introduces two powerful attributes, AllowedValues and DeniedValues, under the System.ComponentModel.DataAnnotations namespace. These attributes streamline input validation by defining acceptable and unacceptable values for API parameters. Let's dive into what they are and how to use them.

What Are AllowedValues and DeniedValues?

  • AllowedValues: Specifies the exact values permitted for an input. If the input value doesn't match one of these, validation fails.
  • DeniedValues: Defines values that should be explicitly rejected. Validation fails if any of these values are provided.

Example Usage:

Here’s how you can apply these attributes to a property:

public class Alert
{
    [AllowedValues("Red", "Yellow", "Green")]
    [DeniedValues("Black", "White")]
    public string? AlertValue { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

How It Works

  • AllowedValues: In the above example, the property AlertValue only accepts "Red", "Yellow", or "Green". Any other value results in validation errors.
  • DeniedValues: Additionally, "Black" and "White" are explicitly disallowed, even if they were among the allowed values.

These attributes are particularly useful in scenarios like:

  • Enum-like constraints: When you want specific, predefined values but don't want to define an enum explicitly.
  • Dynamic policies: Where allowable and disallowed values might vary depending on the context or configuration.

Real-World Example

Consider an API endpoint for setting alert levels in a monitoring system:

[HttpPost]
public IActionResult SetAlert([FromBody] Alert alert)
{
    if (ModelState.IsValid)
    {
        // Process the alert
        return Ok("Alert set successfully.");
    }

    return BadRequest(ModelState);
}
Enter fullscreen mode Exit fullscreen mode

If a user submits a request body like:

{
  "alertValue": "Blue"
}
Enter fullscreen mode Exit fullscreen mode

The API will return a validation error, as "Blue" is not in the list of allowed values.

Key Benefits

  • Ease of Use: No need for custom validation logic—just annotate properties.
  • Improved Readability: Validation rules are directly tied to the data model, making it easy to understand constraints.
  • Consistency: Ensures robust validation across all layers of the application.

Conclusion

The AllowedValues and DeniedValues attributes in .NET 8 simplify input validation for API parameters. By declaratively specifying permitted and restricted values, they enhance the robustness, reliability, and maintainability of your application.

Top comments (1)

Collapse
 
moh_moh701 profile image
mohamed Tayel