Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smailliwcs/f94975668033af954cbd89283e3fcaeb to your computer and use it in GitHub Desktop.
Save smailliwcs/f94975668033af954cbd89283e3fcaeb to your computer and use it in GitHub Desktop.
Conditional required validation
using System.ComponentModel.DataAnnotations;
using System.Reflection;
public sealed class ConditionalRequiredAttribute : RequiredAttribute
{
public override bool RequiresValidationContext
{
get { return true; }
}
public string ConditionalPropertyName { get; private set; }
public ConditionalRequiredAttribute(string conditionalPropertyName)
{
ConditionalPropertyName = conditionalPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo conditionalProperty = validationContext.ObjectType.GetProperty(ConditionalPropertyName);
bool conditionalValue = (bool)conditionalProperty.GetValue(validationContext.ObjectInstance);
if (conditionalValue)
{
return base.IsValid(value, validationContext);
}
else
{
return ValidationResult.Success;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment