Skip to content

[API Proposal]: Have AllowedValuesAttribute and DeniedValuesAttribute support case-insensitive strings #106806

Open
@rjperes

Description

@rjperes

Background and motivation

One of the most common uses of AllowedValues/DeniedValues is with strings, however, they are checked case-sensitive, and we probably want to allow case-insensitive comparisons too. Maybe a case of adding an extra optional constructor argument of type StringComparison, which, of course, would only apply to string values.

API Proposal

namespace System.ComponentModel.DataAnnotations;

public class AllowedValuesAttribute : ValidationAttribute
{
    public AllowedValuesAttribute(StringComparison comparer, params string?[] values) : this(values.OfType<object>().ToArray())
    {
    }

    public AllowedValuesAttribute(params string?[] values) : this(StringComparison.CurrentCulture, values)
    {
    }
}

public class DeniedValuesAttribute : ValidationAttribute
{
    public DeniedValuesAttribute(StringComparison comparer, params string?[] values) : this(values.OfType<object>().ToArray())
    {
    }

    public DeniedValuesAttribute(params string?[] values) : this(StringComparison.CurrentCulture, values)
    {
    }
}

API Usage

[AllowedValues(StringComparison.InvariantCultureIgnoreCase, "red", "green", "blue")]
public string Color { get; set; }

[DeniedValues("a", "e", "i", "o", "u")]
public string Consonants { get; set; }

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions