简体   繁体   中英

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

I have an attribute:

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

on the property named State and I only want it to match given 5 Australian states: { "VIC", "NSW", "QLD", "SA", "TAS", "WA" } . How can I use DataAnnotations for this context?

you can use RegularExpressionAttribute

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

which should only allow VIC, NSW, QLD, TAS, WA, or SA

You can create an attribute inheriting from ValidationAttribute for this.

[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;
    }
}

And use it like this:

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

Here we're using Linq's Contains method on the array.

If you require a case-insensitive option then as Codexer points out you could use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM