1

I have a ValidationAttribute like below which validates that a certain amount of values have been entered on a form. Currently it is only being used on a property with type short?[]

public class RequiredArrayLength : ValidationAttribute
    {
        public int TotalRequired { get; set; }

        public override bool IsValid(object value)
        {
            if(value != null)
            {
                var array = value as short?[];
                return array.Where(v => v.HasValue).Count() >= TotalRequired;
            }
            return false;
        }
    }

Is there a way I can modify this ValidationAttribute so it will work with other numeric arrays such as int?[]

mheptinstall
  • 2,109
  • 3
  • 24
  • 44

1 Answers1

0

One option would be to cast to IEnumerable (System.Collections namespace) and enumerate the collection to determine the number of items in the collection.

IEnumerable collection = value as IEnumerable;
if (collection!= null)
{
    IEnumerator enumerator = collection.GetEnumerator();
    int count = 0;
    while(enumerator.MoveNext())
    {
        count++;
    }
    return count >= TotalRequired;
}
return false;

If you only want to count non-null values, then modify the code to

while(enumerator.MoveNext())
{
    if (enumerator.Current != null)
    {
        count++;
    }
}

If you specifically wanted to limit this to only numeric data types, you can use the .GetType() method of IEnumerable to test the type (for example, C# - how to determine whether a Type is a number).

Community
  • 1
  • 1