LSTANCZYK
9/25/2017 - 1:32 AM

AtLeastOneIsTrue.cs

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class AtLeastOneTrueAttribute : ValidationAttribute
{
    private readonly string _targetProperty;

    public AtLeastOneTrueAttribute(string targetProperty) : base(@"At least one must be selected")
    {
        _targetProperty = targetProperty;
    }

    /// <exception cref="AmbiguousMatchException">More than one property is found with the specified name. See Remarks.</exception>
    /// <exception cref="ArgumentException">Target property must be a boolean!</exception>
    public override bool IsValid(object value)
    {
        var enumerable = value as IEnumerable;
        if (enumerable == null)
        {
            throw new ArgumentException("At least one attribute can only be placed on IEnumerable");
        }

        var enumerator = enumerable.GetEnumerator();

        if (!enumerator.MoveNext())
        {
            return false;
        }

        if (enumerator
            .Current.GetType()
            .GetProperty(_targetProperty).PropertyType != typeof(Boolean))
        {
            throw new ArgumentException("Target property must be a boolean!");
        }

        foreach (var record in enumerable)
        {
            if(Convert.ToBoolean(record.GetType().GetProperty(_targetProperty).GetValue(record)))
            {
                return true;
            }
        }
        return false;
    }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class AtLeastOneTrueAttribute : ValidationAttribute
{
    private readonly string _targetProperty;

    public AtLeastOneTrueAttribute(string targetProperty)
    {
        _targetProperty = targetProperty;
    }

    /// <exception cref="AmbiguousMatchException">More than one property is found with the specified name. See Remarks.</exception>
    public override bool IsValid(object value)
    {
        var enumerable = value as IEnumerable;
        if (enumerable != null)
        {
            var enumerator = enumerable.GetEnumerator();
            
            if (!enumerator.MoveNext() || enumerator
                .Current.GetType()
                .GetProperty(_targetProperty).PropertyType != typeof (Boolean))
            {
                return false;
            }

            foreach (var record in enumerable)
            {
                if(Convert.ToBoolean(record.GetType().GetProperty(_targetProperty).GetValue(record)))
                {
                    return true;
                }
            }
            return false;
        }
        return false;
    }
}