Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Forked from christopherbauer/AtLeastOneIsTrue.cs
Created September 25, 2017 01:32
Show Gist options
  • Save LSTANCZYK/d6945d426a5415ab33a25b3502d641eb to your computer and use it in GitHub Desktop.
Save LSTANCZYK/d6945d426a5415ab33a25b3502d641eb to your computer and use it in GitHub Desktop.
[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;
}
}
[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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment