如何使用 DataAnnotations 检查 属性 只匹配字符串数组

How to use DataAnnotations to check a property only matches an array of string

我有一个属性:

[MaxLength(3)]
public string State { get; set; }

在名为 State 的 属性 上,我只希望它匹配给定的 5 个澳大利亚州: { "VIC", "NSW", "QLD", "SA", "TAS", "WA" }。如何在此上下文中使用 DataAnnotations?

你可以使用RegularExpressionAttribute

[RegularExpression("VIC|NSW|QLD|TAS|WA|SA")]
[MaxLength(3)]
public string State { get; set; }

应该只允许 VIC、NSW、QLD、TAS、WA 或 SA

您可以为此创建一个从 ValidationAttribute 继承的属性。

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class StringRangeAttribute : ValidationAttribute
{       
    public string[] AllowableValues { get; set; }

    public override bool IsValid(object value)
    {
        string actualValue = value as string;

        if (AllowableValues?.Contains(actualValue) == true)
        {
            return true;
        }
        return false;
    }
}

并像这样使用它:

[StringRange(AllowableValues = new string[] { "VIC", "NSW", "QLD", "SA", "TAS", "WA"})]
public string State{ get; set; }

这里我们在数组上使用 Linq 的 Contains 方法。

如果您需要不区分大小写的选项,那么正如 Codexer 指出的那样,您可以使用:

if (AllowableValues?.Contains(actualValue?.ToUpper()) == true)