Skip to content

Instantly share code, notes, and snippets.

@lenidh
Created December 20, 2013 23:48
Show Gist options
  • Save lenidh/8063486 to your computer and use it in GitHub Desktop.
Save lenidh/8063486 to your computer and use it in GitHub Desktop.
Conditional data annotation.
namespace De.Lenidh.Misc
{
using System;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Specifies that a data field value is conditional required.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class RequiredIfAttribute : RequiredAttribute
{
private string dependencyName;
private object requiredValue;
public RequiredIfAttribute(string dependencyName, object requiredValue)
{
this.dependencyName = dependencyName;
this.requiredValue = requiredValue;
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
// Get the dependency property
var dependencyType = validationContext.ObjectInstance.GetType();
var dependency = dependencyType.GetProperty(this.dependencyName);
if (dependency == null)
{
var msg = string.Format("Property '{0}' not found.", this.dependencyName);
throw new InvalidOperationException(msg);
}
var dependencyValue = dependency.GetValue(validationContext.ObjectInstance);
if (this.requiredValue == null && dependencyValue == null)
return base.IsValid(value, validationContext);
if (this.requiredValue != null && this.requiredValue.Equals(dependencyValue))
return base.IsValid(value, validationContext);
// Always successful, if dependency value and required value not equal.
return ValidationResult.Success;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment