Open
Description
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